﻿using Coldairarrow.Entity.Base;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DingReving;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.IT;
using Coldairarrow.Entity.PB;
using Coldairarrow.Entity.Print;
using Coldairarrow.Entity.TD;
using Coldairarrow.IBusiness.DTO;
using Coldairarrow.Util;
using Coldairarrow.Util.ClassLibrary;
using Coldairarrow.Util.Helper;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Coldairarrow.Business.TD
{
    public partial class TD_ReceivingBusiness : BaseBusiness<TD_Receiving>, ITD_ReceivingBusiness, ITransientDependency
    {
     

        #region 外部接口

        public async Task<PageResult<TD_Receiving>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<TD_Receiving>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<TD_Receiving, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<PageResult<TD_Receivinginfo>> GetDataListinfo(PageInput<ReceivingConditionDTO> input)
        {
            var search = input.Search;
            Expression<Func<TD_Receiving, Base_Department, PB_Supplier, Base_User, PB_Customer, Base_User, Base_EnumItem, TD_Receivinginfo>> select = (a, b, c, d, e, f, g) => new TD_Receivinginfo
            {
                StorIdName = b.Name,
                SupIdName = c.Name,
                ConfirmUserIdName = d.RealName,
                CusIDName = e.Name,
                AuditUserIdName = f.RealName,
                RType = g.Name,

            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<Base_Department>() on a.StorId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_Supplier>() on a.SupId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<Base_User>() on a.CreatorId equals d.Id into ad
                    from d in ad.DefaultIfEmpty()
                    join e in Db.GetIQueryable<PB_Customer>() on a.CusID equals e.Id into ae
                    from e in ae.DefaultIfEmpty()
                    join f in Db.GetIQueryable<Base_User>() on a.AuditUserId equals f.Id into af
                    from f in af.DefaultIfEmpty()
                    join g in Db.GetIQueryable<Base_EnumItem>() on a.Type equals g.Code into ag
                    from g in ag.Where(u => u.EnumCode.Contains("ReceiveType")).DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d, e, f, g);
            if (!search.MaterName.IsNullOrEmpty())
            {
                //子表数据
                Expression<Func<TD_RecDetail, PB_Material, TD_RecDetailDTO>> selectk = (a, b) => new TD_RecDetailDTO
                {

                    MaterialIdName = b.Name,
                    MaterialldCode = b.Code,
                    MateSpce = b.Spec
                };
                selectk = selectk.BuildExtendSelectExpre();
                var k = from a in Db.GetIQueryable<TD_RecDetail>().AsExpandable()
                        join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        select @selectk.Invoke(a, b);

                var res = await k.Where(x => x.MaterialIdName.Contains(search.MaterName) || x.MaterialldCode.Contains(search.MaterName) || x.MateSpce.Contains(search.MaterName)).ToListAsync();
                var list = res.GroupBy(x => new { x.RecId }).Select(x => new { RecId = x.Key.RecId });
                List<String> names = new List<string>();

                foreach (var item in list)
                {
                    names.Add(item.RecId);
                }
                q = q.Where(x => names.Contains(x.Id));
            }


            //var res = k.ToListAsync();
            if (!search.Keyword.IsNullOrEmpty())
            {
                var keyword = $"%{search.Keyword}%";
                q = q.Where(x =>
                      EF.Functions.Like(x.Id, keyword)
                      || EF.Functions.Like(x.RefCode, keyword)
                      || EF.Functions.Like(x.SupIdName, keyword)

                      );
            }
            if (!search.Status.IsNullOrEmpty())
            {
                q = q.Where(x => x.Status == search.Status);
            }
            if (!search.StartDate.IsNullOrEmpty() && !search.EndDate.IsNullOrEmpty())
            {
                q = q.Where(x => (search.StartDate <= x.RecTime) && (x.RecTime <= search.EndDate));
            }
            if (!search.ConfirmUserIdName.IsNullOrEmpty())
            {
                q = q.Where(x => x.ConfirmUserIdName.Contains(search.ConfirmUserIdName)); ;
            }
            if (!search.Type.IsNullOrEmpty())
            {
                q = q.Where(x => x.Type == search.Type);
            }

            q = q.Where(x => _operator.Property.DeptIds.Contains(x.DeptId));
            return await q.GetPageResultAsync(input);
        }

        public async Task<List<TD_Receivinglistinfo>> GetDataListInfos(string ParentId)
        {
            Expression<Func<TD_Receiving, Base_Department, PB_Supplier, Base_User, PB_Customer, Base_User, PB_WarehousingNotice, PB_PackList, TD_Receivinglistinfo>> select = (a, b, c, d, e, f, g, h) => new TD_Receivinglistinfo
            {
                StorIdName = b.Name,
                SupIdName = c.Name,
                ConfirmUserIdName = d.RealName,
                AuditUserIdName = d.RealName,
                CusIDName = e.Name,
                CusIDPhone = e.Phone,
                PackId = h.Id,
                PackNums = h.Nums,

            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<Base_Department>() on a.StorId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_Supplier>() on a.SupId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<Base_User>() on a.ConfirmUserId equals d.Id into ad
                    from d in ad.DefaultIfEmpty()
                    join e in Db.GetIQueryable<PB_Customer>() on a.CusID equals e.Id into ae
                    from e in ae.DefaultIfEmpty()
                    join f in Db.GetIQueryable<Base_User>() on a.AuditUserId equals f.Id into af
                    from f in af.DefaultIfEmpty()
                    join g in Db.GetIQueryable<PB_WarehousingNotice>() on a.RefCode equals g.Id into ag
                    from g in ag.DefaultIfEmpty()
                    join h in Db.GetIQueryable<PB_PackList>() on g.Id equals h.NoticeId into gh
                    from h in gh.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d, e, f, g, h);
            List<TD_Receivinglistinfo> listdata = new List<TD_Receivinglistinfo>();
            var qdata = await q.Where(x => x.Id == ParentId).FirstOrDefaultAsync();
            Expression<Func<TD_RecDetail, Base_Department, PB_Location, PB_Material, PB_Measure, IT_LocalMaterial, TD_RecDetailDTO>> selects = (a, b, c, d, e, f) => new TD_RecDetailDTO
            {
                StorIdName = b.Name,
                LocaIdName = c.Name,
                MaterialIdName = d.Name,
                MeasureIdName = e.Name,
                MaterialldCode = d.Code,
                MateSpce = d.Spec,
                PackageNum = d.PackageNum,

                BaoNum = d.IsSingle == true ? 0 : Math.Ceiling(a.PlanNum / d.PackageNum),
                Availablequantity = f.Nums_N + f.Nums_O - f.Nums_R,//可用数量
                SuggestedLocation = f.Nums_N + f.Nums_O - f.Nums_R != 0 ? "建议" : (f.Nums_N + f.Nums_O) == 0 || (f.Nums_N + f.Nums_O) - f.Nums_R == 0 ? "  " : "",
            };
            selects = selects.BuildExtendSelectExpre();
            var k = from a in Db.GetIQueryable<TD_RecDetail>().AsExpandable()
                    join b in Db.GetIQueryable<Base_Department>() on a.StorId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_Location>() on a.LocaId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<PB_Material>() on a.MaterialId equals d.Id into ad
                    from d in ad.DefaultIfEmpty()
                    join e in Db.GetIQueryable<PB_Measure>() on d.storageId equals e.Id into de
                    from e in de.DefaultIfEmpty()
                    join f in Db.GetIQueryable<IT_LocalMaterial>() on c.Id equals f.LocalId into cf
                    from f in cf.DefaultIfEmpty()
                    select @selects.Invoke(a, b, c, d, e, f);
            k = k.Where(x => x.RecId == qdata.Id);
            var res = await k.ToListAsync();
            List<string> materialids = new List<string>();
            foreach (var item in res)
            {
                materialids.Add(item.MaterialId);
            }
            //string sqlMain = @" select c.Id,c.Nums,c.BoxName,a.MaterialId,d.`Name` as MaterialName,e.`Name` as MaterialTypeName,c.QrCode,f.`Name` as DeptName,a.RecId from PB_JobBookingQrCode as a join PB_PackListInfo as b on a.Id=b.JobBookingId join PB_PackList as c on b.PackId=c.Id join PB_Material as d on a.MaterialId=d.Id join  PB_MaterialType as e on d.MaterialTypeId=e.Id join Base_Department as f on c.DeptId=f.Id where a.RecId='" + qdata.Id + "' and a.MaterialId in ('" + string.Join("','", materialids.ToArray()) + "')    GROUP BY c.Id,c.BoxName,a.MaterialId,d.`Name`,e.`Name`,c.QrCode,f.`Name`,a.RecId ; ";
            string sqlMain = @" select b.Id,b.Nums,b.BoxName,a.MaterialId,a.MaterialName,b.QrCode,a.RecId from pb_jobbookingqrcode as a join pb_packlist as b on a.PackId=b.Id where a.RecId='" + qdata.Id + "' and a.MaterialId in ('" + string.Join("','", materialids.ToArray()) + "') group by b.Id,b.Nums,b.BoxName,a.MaterialId,a.MaterialName,b.QrCode,a.RecId ";
            List<PB_PackListRecDTO> PackListlist = await Db.GetListBySqlAsync<PB_PackListRecDTO>(sqlMain);

            foreach (var item in res)
            {
                var itemdata = PackListlist.Where(x => x.MaterialId == item.MaterialId).ToList();
                item.PB_PackListRecDTO = itemdata;
            }

            //var list = res.GroupBy(x => new { x.MaterialIdName, x.MaterialldCode, }).Select(x => new { MaterialIdName = x.Key.MaterialIdName, MaterialldCode = x.Key.MaterialldCode, PlanNum = x.Sum(i => i.PlanNum) });
            List<TD_Receivinglistinfo> infolist = new List<TD_Receivinglistinfo>();
            TD_Receivinglistinfo pblist = new TD_Receivinglistinfo();
            pblist.Id = qdata.Id;
            pblist.QrCode = qdata.QrCode;
            pblist.CreatorId = qdata.CreatorId;
            pblist.StorIdName = qdata.StorIdName;
            pblist.Code = qdata.Code;
            pblist.OrderTime = qdata.OrderTime;
            pblist.RecTime = qdata.RecTime;
            pblist.Type = qdata.Type;
            pblist.RefCode = qdata.RefCode;
            pblist.Status = qdata.Status;
            pblist.SupIdName = qdata.SupIdName;
            pblist.TotalNum = qdata.TotalNum;
            pblist.InNum = qdata.InNum;
            pblist.TotalAmt = qdata.TotalAmt;
            pblist.Remarks = qdata.Remarks;
            pblist.ConfirmUserIdName = qdata.ConfirmUserIdName;
            pblist.ConfirmTime = qdata.ConfirmTime;
            pblist.AuditUserIdName = qdata.AuditUserIdName;
            pblist.AuditeTime = qdata.AuditeTime;
            pblist.CreateTime = qdata.CreateTime;
            pblist.CreatorId = qdata.CreatorId;
            pblist.CusIDName = qdata.CusIDName;
            pblist.CusIDPhone = qdata.CusIDPhone;
            pblist.PackId = qdata.PackId;
            pblist.PackNums = qdata.PackNums;
            pblist.Subdata = res;
 //           List<PB_PackListRecDTO> DDDDD = new List<PB_PackListRecDTO>();
 //           string sqlMain2 = @"SELECT	c.Id,c.Nums,a.RecId FROM PB_JobBookingQrCode AS a
	//JOIN PB_PackListInfo AS b ON a.Id = b.JobBookingId
	//JOIN PB_PackList AS c ON b.PackId = c.Id
	//JOIN PB_Material AS d ON a.MaterialId = d.Id
	//JOIN PB_MaterialType AS e ON d.MaterialTypeId = e.Id
	//JOIN Base_Department AS f ON c.DeptId = f.Id WHERE
	//a.RecId = '" + qdata.Id + "'   AND c.PackageType = 1  GROUP BY c.Id,a.RecId";
 //           DDDDD = await Db.GetListBySqlAsync<PB_PackListRecDTO>(sqlMain2);
 //           if (DDDDD.Count > 0)
 //           {
 //               pblist.DDD = DDDDD;
 //           }
            infolist.Add(pblist);

            return infolist;
        }


        /// <summary>
        /// 获取收货单的已入库的明细信息
        /// </summary>
        /// <param name="receivingId">收货单Id</param>
        /// <returns></returns>
        public async Task<List<PB_UpLoadListDataDTO>> GetLocalMaterial_SListAsync(string receivingId)
        {
            //            string sqlMain = @"select *,ROW_NUMBER() over(order by CreateTime desc) as rowsid from ( 
            //select a.Id,a.PackId,a.MaterialId,a.CirBillId,a.Nums as StockNumber,b.Id as BoxNo,b.Name as BoxName,(concat(d.`Name`,'/',e.`Name`,'/',c.`Name`)) as LocalName,b.Spec as MaterialSpec,a.CreateTime,a.LocalId as LocationId,f.StorId,'1' as OldOrNew,a.JobId from  PB_UpLoadList as a join PB_Material as b on a.MaterialId=b.Id  join PB_Location as c on a.LocalId=c.Id join PB_StorArea as d on c.AreaId=d.Id join PB_Rack as e on c.RackId=e.Id join PB_Location as f on a.LocalId=f.Id where a.ParentId='{0}' and a.PackId='' and a.JobId=''
            //UNION ALL 
            //select '' as Id,PackId,'' as MaterialId,CirBillId,SUM(StockNumber) as StockNumber,BoxNo,BoxName,LocalName, '' as MaterialSpec,CreateTime,LocationId,StorId,OldOrNew,'' as JobId from (select a.PackId,a.Nums as StockNumber,b.BoxNo,b.BoxName,(concat(d.`Name`,'/',e.`Name`,'/',c.`Name`)) as LocalName,DATE_FORMAT(a.CreateTime,'%Y-%m-%d') as CreateTime,a.LocalId as LocationId,f.StorId,b.OldOrNew,a.CirBillId from PB_UpLoadList as a join PB_PackList as b on a.PackId=b.Id join PB_Location as c on a.LocalId=c.Id join PB_StorArea as d on c.AreaId=d.Id join PB_Rack as e on c.RackId=e.Id join PB_Location as f on a.LocalId=f.Id  where a.ParentId='{0}' and b.PackageType=1 )as t group by PackId,BoxNo,BoxName,LocalName,CreateTime,LocationId,StorId,OldOrNew,CirBillId
            //UNION ALL 
            //select '' as Id,a.PackId,a.MaterialId,a.CirBillId,a.Nums as StockNumber,b.BoxNo,b.BoxName,(concat(d.`Name`,'/',e.`Name`,'/',c.`Name`)) as LocalName,f.Spec as MaterialSpec,a.CreateTime,a.LocalId as LocationId,g.StorId,b.OldOrNew,'' as JobId from PB_UpLoadList as a join PB_PackList as b on a.PackId=b.Id join PB_Location as c on a.LocalId=c.Id join PB_StorArea as d on c.AreaId=d.Id join PB_Rack as e on c.RackId=e.Id join PB_Material as f on a.MaterialId=f.Id join PB_Location as g on a.LocalId=g.Id where a.ParentId='{0}' and b.PackageType=0 
            //UNION ALL
            //select a.Id,a.PackId,a.MaterialId,a.CirBillId,a.Nums as StockNumber,a.JobId as BoxNo,b.Name as BoxName,(concat(d.`Name`,'/',e.`Name`,'/',c.`Name`)) as LocalName,b.Spec as MaterialSpec,a.CreateTime,a.LocalId as LocationId,f.StorId,g.OldOrNew,a.JobId from  PB_UpLoadList as a join PB_Material as b on a.MaterialId=b.Id  join PB_Location as c on a.LocalId=c.Id join PB_StorArea as d on c.AreaId=d.Id join PB_Rack as e on c.RackId=e.Id join PB_Location as f on a.LocalId=f.Id join IT_LocalDetail as g on a.JobId=g.JobId where a.ParentId='{0}' and a.PackId='' and a.JobId!=''
            //) as t ";
            string sqlMain = @"select *,ROW_NUMBER() over(order by CreateTime desc) as rowsid from ( 
select a.Id,a.PackId,a.MaterialId,a.CirBillId,a.Nums as StockNumber,b.Id as BoxNo,b.Name as BoxName,(concat(d.`Name`,'/',e.`Name`,'/',c.`Name`)) as LocalName,b.Spec as MaterialSpec,a.CreateTime,a.LocalId as LocationId,f.StorId,'1' as OldOrNew,a.JobId from  PB_UpLoadList as a join PB_Material as b on a.MaterialId=b.Id  join PB_Location as c on a.LocalId=c.Id join PB_StorArea as d on c.AreaId=d.Id join PB_Rack as e on c.RackId=e.Id join PB_Location as f on a.LocalId=f.Id where a.ParentId='{0}' and a.PackId='' and a.JobId=''
UNION ALL 
select '' as Id,PackId,'' as MaterialId,CirBillId,SUM(StockNumber) as StockNumber,BoxNo,BoxName,LocalName, '' as MaterialSpec,CreateTime,LocationId,StorId,OldOrNew,'' as JobId from (select a.PackId,a.Nums as StockNumber,b.BoxNo,b.BoxName,(concat(d.`Name`,'/',e.`Name`,'/',c.`Name`)) as LocalName,DATE_FORMAT(a.CreateTime,'%Y-%m-%d') as CreateTime,a.LocalId as LocationId,f.StorId,b.OldOrNew,a.CirBillId from PB_UpLoadList as a join PB_PackList as b on a.PackId=b.Id join PB_Location as c on a.LocalId=c.Id join PB_StorArea as d on c.AreaId=d.Id join PB_Rack as e on c.RackId=e.Id join PB_Location as f on a.LocalId=f.Id  where a.ParentId='{0}' and b.PackageType=1 )as t group by PackId,BoxNo,BoxName,LocalName,CreateTime,LocationId,StorId,OldOrNew,CirBillId
UNION ALL 
select '' as Id,a.PackId,a.MaterialId,a.CirBillId,a.Nums as StockNumber,b.BoxNo,b.BoxName,(concat(d.`Name`,'/',e.`Name`,'/',c.`Name`)) as LocalName,f.Spec as MaterialSpec,a.CreateTime,a.LocalId as LocationId,g.StorId,b.OldOrNew,'' as JobId from PB_UpLoadList as a join PB_PackList as b on a.PackId=b.Id join PB_Location as c on a.LocalId=c.Id join PB_StorArea as d on c.AreaId=d.Id join PB_Rack as e on c.RackId=e.Id join PB_Material as f on a.MaterialId=f.Id join PB_Location as g on a.LocalId=g.Id where a.ParentId='{0}' and b.PackageType=0 
UNION ALL
select a.Id,a.PackId,a.MaterialId,a.CirBillId,a.Nums as StockNumber,a.JobId as BoxNo,b.Name as BoxName,(concat(d.`Name`,'/',e.`Name`,'/',c.`Name`)) as LocalName,b.Spec as MaterialSpec,a.CreateTime,a.LocalId as LocationId,f.StorId,'1' AS OldOrNew,a.JobId from  PB_UpLoadList as a join PB_Material as b on a.MaterialId=b.Id  join PB_Location as c on a.LocalId=c.Id join PB_StorArea as d on c.AreaId=d.Id join PB_Rack as e on c.RackId=e.Id join PB_Location as f on a.LocalId=f.Id where a.ParentId='{0}' and a.PackId='' and a.JobId<>'') as t ";
            string sql = string.Format(sqlMain, receivingId);
            return await Db.GetListBySqlAsync<PB_UpLoadListDataDTO>(sql);
        }
      
        /// <summary>
        /// 扫描物料
        /// </summary>
        /// <param name="packqrcode">物料二维码</param>
        /// <param name="recqrcode">收货单二维码</param>
        /// <returns></returns>
        public async Task<PB_MaterialRecDetailDTO> GetMaterialRecDetailDataAsync(string packqrcode, string recqrcode)
        {
            //获取物料Id
            var packmodel = packqrcode.Split(',');
            string packid = string.Empty;
            if (packmodel.Length > 2) {
                packid = packmodel?[3].ToString();
            }
            else {
                packid = packmodel?[1].ToString();
            }
            //合并重复物料指向新的物料Id
            PB_Material materdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == packid).FirstOrDefaultAsync();
            if (!materdata.TransferId.IsNullOrEmpty())
            {
                packid = materdata.TransferId;
            }

            //收货单Id
            string recid = recqrcode.Split(',')?[1].ToString();
            Expression<Func<PB_Material, TD_RecDetail, PB_MaterialRecDetailDTO>> select = (a, b) => new PB_MaterialRecDetailDTO
            {
                Nums = b.RecNum - b.InNum,
                RecId = b.RecId
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_Material>().AsExpandable()
                    join b in Db.GetIQueryable<TD_RecDetail>() on a.Id equals b.MaterialId into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);
            return await q.Where(x => x.Id == packid && x.RecId == recid).FirstOrDefaultAsync();
        }

        /// <summary>
        /// 根据收货单上架入库
        /// </summary>
        /// <param name="data"></param>
        /// <param name="_redisOptions"></param>
        /// <returns></returns>
        [Transactional]
        public async Task SaveShelfStorageAsync(WarehousingDTO data, RedisOptions _redisOptions)
        {
            Base_User bdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            //查询收货单是否审核过
            string ReceivingId = data.receqroce.Split(',')?[1].ToString();
            var recedata = await Db.GetIQueryable<TD_Receiving>().Where(x => x.Id == ReceivingId).FirstOrDefaultAsync();
            if (recedata.Status == 3)
            {
                //获取货位id
                string LocationId = data.Locationqrcode.Split(',')?[1].ToString();

                //获取货位信息
                var Locationdata = await Db.GetIQueryable<PB_Location>().Where(x => x.Id == LocationId).FirstOrDefaultAsync();

                if (Locationdata.StorId != recedata.StorId)
                {
                    throw new BusException("请检查扫描的货位是否是收货单对应仓库下的货位");
                }

                //获取包Id
                string packId = string.Empty;
                string materialId = string.Empty;
                string cirbillId = string.Empty;
                string JobId = string.Empty;
                string packmodel = data.packqrcode.Split(',')?[0].ToString();
                if (packmodel == "13")
                {
                    packId = data.packqrcode.Split(',')?[1].ToString();
                }
                else if (packmodel == "04")
                {
                    var model = data.packqrcode.Split(',');
                    if (model.Length > 2)
                    {
                        if (model.Length < 4)
                        {
                            throw new BusException("请扫描正确的二维码信息");
                        }
                        else
                        {
                            materialId = model?[3].ToString();
                        }
                    }
                    else
                    {
                        materialId = model?[1].ToString();
                    }
                    //合并重复物料指向新的物料Id
                    PB_Material materdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == materialId).FirstOrDefaultAsync();
                    if (!materdata.TransferId.IsNullOrEmpty())
                    {
                        materialId = materdata.TransferId;
                    }
                }
                else if (packmodel == "31")
                {
                    cirbillId = data.packqrcode.Split(',')?[1].ToString();
                }
                else if (packmodel == "14")
                {
                    JobId = data.packqrcode.Split(',')?[1].ToString();
                    //查询单个成品是否绑定包信息
                    PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == JobId).FirstOrDefaultAsync();
                    if (jobdata != null)
                    {
                        if (!jobdata.PackId.IsNullOrEmpty())
                        {
                            packmodel = "13";
                            packId = jobdata.PackId;
                        }
                    }
                }

                List<PB_Stock> StockList = new List<PB_Stock>();
                List<PB_StockLog> StockLogList = new List<PB_StockLog>();
                List<PB_UpLoadList> UpLoadListList = new List<PB_UpLoadList>();
                List<IT_LocalDetail> LocalDetailList = new List<IT_LocalDetail>();
                List<IT_LocalMaterial> LocalMaterialList = new List<IT_LocalMaterial>();
                List<PB_JobBookingQrCode> JobBookingQrCode = new List<PB_JobBookingQrCode>();
                string sqlMain = string.Empty;

                PB_WarehousingNotice noticedata = await Db.GetIQueryable<PB_WarehousingNotice>().Where(x => x.Id == recedata.RefCode).FirstOrDefaultAsync();
                if (packmodel == "13")
                {
                    //获取包信息
                    var packdata = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == packId).FirstOrDefaultAsync();
                    if (packdata != null)
                    {
                        if (packdata.Status == 5)
                        {
                            throw new BusException("包码已作废,请做补码处理");
                        }
                        if (packdata.Status == 0 || packdata.Status == 1)
                        {
                            throw new BusException("请扫描待上架的包");
                        }
                        //查询当前入库的包是否已入库
                        var detatildata = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.PackId == packId).ToListAsync();
                        //判断是否为混合包，不是混合包
                        if (packdata.PackageType == 0)
                        {
                            //获取物料信息
                            var Materialdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == packdata.MaterialId).FirstOrDefaultAsync();

                            //收货单类型等于采购收货
                            if (recedata.Type == "Purchase")
                            {
                                //修改包的入库通知单Id
                                sqlMain += @" update PB_PackList set NoticeId='" + recedata.RefCode + "' where Id='" + packId + "'; ";
                                //await ExecuteSqlAsync(sqlMain);
                                //修改包对应的成品码信息为收货单Id
                                Expression<Func<PB_JobBookingQrCode, PB_PackListInfo, PB_Material, PB_PackListInfoDetail>> select = (a, b, c) => new PB_PackListInfoDetail
                                {
                                    PackId = b.PackId,
                                    storageId = c.storageId,
                                    Price = c.Price
                                };
                                select = select.BuildExtendSelectExpre();
                                var q = from a in Db.GetIQueryable<PB_JobBookingQrCode>().AsExpandable()
                                        join b in Db.GetIQueryable<PB_PackListInfo>() on a.Id equals b.JobBookingId into ab
                                        from b in ab.DefaultIfEmpty()
                                        join c in Db.GetIQueryable<PB_Material>() on a.MaterialId equals c.Id into ac
                                        from c in ac.DefaultIfEmpty()
                                        select @select.Invoke(a, b, c);
                                var infodetail = await q.Where(x => x.PackId == packId && x.PurchaseId == recedata.OrderId).ToListAsync();
                                string jobids = string.Empty;
                                foreach (var item in infodetail)
                                {
                                    jobids += "'" + item.Id + "',";
                                }
                                jobids = jobids.Substring(0, jobids.Length - 1);
                                //修改成品码对应的收货单
                                sqlMain += @" update PB_JobBookingQrCode set RecId='" + recedata.Id + "' where Id in (" + jobids + ") and PurchaseId='" + recedata.OrderId + "'; ";
                                //await ExecuteSqlAsync(sqlMain);
                                string memoname = "";
                                if (noticedata.Memo.IsNullOrEmpty())
                                {
                                    memoname = packdata.BoxName;
                                }
                                else
                                {
                                    memoname = noticedata.Memo + "," + packdata.BoxName;
                                }
                                //修改入库通知单的说明字段
                                sqlMain += @"update PB_WarehousingNotice set Memo='" + memoname + "' where Id='" + recedata.RefCode + "'; ";
                            }
                            //退货收货
                            else if (recedata.Type == "ReceReturn")
                            {
                                //修改包的入库通知单Id
                                sqlMain += @" update PB_PackList set NoticeId='" + recedata.RefCode + "' where Id='" + packId + "'; ";
                                //修改包内成品对应的收货单
                                sqlMain += @" update PB_JobBookingQrCode set RecId='" + ReceivingId + "' where PackId='" + packId + "'; ";
                            }
                            else
                            {
                                List<PB_JobBookingQrCode> joblist = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.RecId == ReceivingId && x.PackId == packId).ToListAsync();
                                if (joblist.Count == 0)
                                {
                                    throw new BusException("请检查此包是否和收货单匹配");
                                }
                            }
                            TD_RecDetail RecDetail = await Db.GetIQueryable<TD_RecDetail>().Where(x => x.RecId == ReceivingId && x.MaterialId == packdata.MaterialId).FirstOrDefaultAsync();
                            if (RecDetail == null)
                            {
                                throw new BusException("请检查此包物料是否和收货单匹配");
                            }

                            var trueorfalse = await _check.GetTrueOrFalse(Materialdata.Id, Locationdata.StorId, LocationId);
                            if (trueorfalse.boolType == false)
                            {
                                throw new BusException("仓库物料正在盘点中禁止上架入库");
                            }
                            if (detatildata.Count == 0)
                            {
                                //插入库存
                                PB_Stock stockdata = new PB_Stock();
                                stockdata.Id = IdHelper.GetId();
                                stockdata.PackId = packId;
                                stockdata.StorId = Locationdata.StorId;
                                stockdata.LocationId = LocationId;
                                stockdata.StockNumber = packdata.Nums;
                                stockdata.MaterialId = packdata.MaterialId;
                                stockdata.CreatorId = _operator.UserId;
                                stockdata.CreatorName = bdata.RealName;
                                stockdata.CreateTime = DateTime.Now;
                                stockdata.OperatorId = _operator.UserId;
                                stockdata.OrderID = ReceivingId;
                                stockdata.Type = 1;
                                stockdata.OldOrNew = packdata.OldOrNew;
                                stockdata.CirBillId = "";
                                stockdata.JobId = "";
                                StockList.Add(stockdata);

                                //插入库日志表
                                PB_StockLog lodata = new PB_StockLog();
                                lodata.Id = IdHelper.GetId();
                                lodata.PackId = packId;
                                lodata.StorId = Locationdata.StorId;
                                lodata.LocationId = LocationId;
                                lodata.MaterialId = packdata.MaterialId;
                                lodata.StockNumber = packdata.Nums;
                                lodata.CreatorId = _operator.UserId;
                                lodata.CreatorName = bdata.RealName;
                                lodata.OperatorId = _operator.UserId;
                                lodata.OrderID = ReceivingId;
                                lodata.CreateTime = DateTime.Now;
                                lodata.Type = 1;
                                lodata.State = 0;
                                lodata.OldOrNew = packdata.OldOrNew;
                                lodata.CirBillId = "";
                                lodata.JobId = "";
                                StockLogList.Add(lodata);

                                //收货单物料明细对应的包信息
                                PB_UpLoadList updata = new PB_UpLoadList();
                                updata.Id = IdHelper.GetId();
                                updata.ParentId = ReceivingId;
                                updata.StorId = Locationdata.StorId;
                                updata.LocalId = LocationId;
                                updata.PackId = packId;
                                updata.MaterialId = packdata.MaterialId;
                                updata.Nums = packdata.Nums;
                                updata.CreatorId = _operator.UserId;
                                updata.CreatorRealName = bdata.RealName;
                                updata.CreateTime = DateTime.Now;
                                updata.Deleted = false;
                                updata.CirBillId = "";
                                updata.JobId = "";
                                UpLoadListList.Add(updata);

                                //库存明细表
                                IT_LocalDetail detdata = new IT_LocalDetail();
                                detdata.Id = IdHelper.GetId();
                                detdata.StorId = Locationdata.StorId;
                                detdata.LocalId = LocationId;
                                detdata.MaterialId = packdata.MaterialId;
                                detdata.MeasureId = Materialdata.storageId;
                                detdata.InTime = DateTime.Now;
                                detdata.CreateTime = DateTime.Now;
                                detdata.CreatorId = _operator.UserId;
                                detdata.Deleted = false;
                                detdata.Num = packdata.Nums;
                                detdata.BarCode = data.packqrcode;
                                detdata.PackId = packId;
                                detdata.Price = Materialdata.Price;
                                detdata.Amount = packdata.Nums * Materialdata.Price;
                                detdata.OldOrNew = packdata.OldOrNew;
                                detdata.RecId = ReceivingId;
                                detdata.JobId = "";
                                LocalDetailList.Add(detdata);

                                //查询货架上存放货物存汇总表是否存在
                                var materdata = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == packdata.MaterialId && x.StorId == Locationdata.StorId && x.LocalId == LocationId).FirstOrDefaultAsync();
                                if (materdata == null)
                                {
                                    //不存在新增
                                    IT_LocalMaterial itdata = new IT_LocalMaterial();
                                    itdata.Id = IdHelper.GetId();
                                    itdata.MaterialId = packdata.MaterialId;
                                    itdata.StorId = Locationdata.StorId;
                                    itdata.LocalId = LocationId;
                                    if (packdata.OldOrNew == 0)
                                    {
                                        itdata.Nums_O = Convert.ToDouble(packdata.Nums);
                                        itdata.Nums_N = 0;
                                    }
                                    else if (packdata.OldOrNew == 1)
                                    {
                                        itdata.Nums_O = 0;
                                        itdata.Nums_N = Convert.ToDouble(packdata.Nums);
                                    }
                                    itdata.CreatorId = _operator.UserId;
                                    itdata.CreateTime = DateTime.Now;
                                    itdata.Deleted = false;
                                    itdata.AreaId = Locationdata.AreaId;
                                    itdata.RackId = Locationdata.RackId;
                                    itdata.ScanNum = Convert.ToDouble(packdata.Nums);
                                    itdata.CheckNum = 0;
                                    LocalMaterialList.Add(itdata);
                                }
                                else
                                {
                                    if (packdata.OldOrNew == 0)
                                    {
                                        sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)+" + packdata.Nums + ",ScanNum=IFNULL(ScanNum,0)+'" + packdata.Nums + "' where StorId='" + Locationdata.StorId + "' and LocalId='" + LocationId + "' and MaterialId='" + packdata.MaterialId + "'; ";
                                    }
                                    else if (packdata.OldOrNew == 1)
                                    {
                                        sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + packdata.Nums + ",ScanNum=IFNULL(ScanNum,0)+'" + packdata.Nums + "' where StorId='" + Locationdata.StorId + "' and LocalId='" + LocationId + "' and MaterialId='" + packdata.MaterialId + "'; ";
                                    }
                                }

                                //修改物料审核前数量
                                sqlMain += @" update PB_Material set ScanNum=IFNULL(ScanNum,0)+" + packdata.Nums + " where Id='" + packdata.MaterialId + "'; ";

                                //修改包的状态为已入库
                                sqlMain += @" UPDATE PB_PackList SET  Status= '3',InStorTime=NOW(),InStorUserId='" + _operator.UserId + "',InStorUserName='" + bdata.RealName + "' WHERE id='" + packId + "'; ";

                                //修改收货单的入库数量
                                sqlMain += @" update TD_RecDetail set InNum=IFNULL(InNum,0)+" + packdata.Nums + " where RecId='" + ReceivingId + "' and MaterialId='" + packdata.MaterialId + "' ;";

                                //查询包码对应的生产任务单
                                List<PB_JobBookingQrCode> JobBookingQrCodeList = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.RecId == ReceivingId && x.PackId == packId).ToListAsync();
                                if (JobBookingQrCodeList.Count > 0)
                                {
                                    var codegroup = JobBookingQrCodeList.GroupBy(x => new { x.OrderDetailId, x.MaterialId }).Select(x => new { OrderDetailId = x.Key.OrderDetailId, MaterialId = x.Key.MaterialId, Nums = x.Count() }).ToList();
                                    if (codegroup.Count > 0)
                                    {
                                        foreach (var item in codegroup)
                                        {
                                            sqlMain += $@"  update PB_ProductionOrderDetail set CompleteNums=IFNULL(CompleteNums,0)+{item.Nums},WarehousingTime=NOW() where Id='{ item.OrderDetailId }'; ";
                                        }
                                    }
                                }

                            }
                            else
                            {
                                throw new BusException("不能重复入库");
                            }
                        }
                        else if (packdata.PackageType == 1)
                        {
                            List<PB_JobBookingQrCode> infodetail = new List<PB_JobBookingQrCode>();
                            //采购收货
                            if (recedata.Type == "Purchase")
                            {
                                //修改包的入库通知单Id
                                sqlMain += @" update PB_PackList set NoticeId='" + recedata.RefCode + "' where Id='" + packId + "'; ";
                                //await ExecuteSqlAsync(sqlMain);
                                infodetail = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.PackId == packId && x.PurchaseId == recedata.OrderId && x.RecId == ReceivingId).ToListAsync();
                                string jobids = string.Empty;
                                foreach (var item in infodetail)
                                {
                                    jobids += "'" + item.Id + "',";
                                }
                                jobids = jobids.Substring(0, jobids.Length - 1);
                                //修改成品码对应的收货单
                                sqlMain += @" update PB_JobBookingQrCode set RecId='" + recedata.Id + "' where Id in (" + jobids + ") and PurchaseId='" + recedata.OrderId + "'; ";
                                string memoname = "";
                                if (noticedata.Memo.IsNullOrEmpty())
                                {
                                    memoname = packdata.BoxName;
                                }
                                else
                                {
                                    memoname = noticedata.Memo + "," + packdata.BoxName;
                                }
                                //修改入库通知单的说明字段
                                sqlMain += @" update PB_WarehousingNotice set Memo='" + memoname + "' where Id='" + recedata.RefCode + "'; ";
                            }
                            //退货收货
                            else if (recedata.Type == "ReceReturn")
                            {
                                //修改包的入库通知单Id
                                sqlMain += @" update PB_PackList set NoticeId='" + recedata.RefCode + "' where Id='" + packId + "'; ";
                                //修改包内成品对应的收货单
                                sqlMain += @" update PB_JobBookingQrCode set RecId='" + ReceivingId + "' where PackId='" + packId + "'; ";
                                infodetail = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.PackId == packId).ToListAsync();
                            }
                            else
                            {
                                infodetail = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.PackId == packId && x.RecId == ReceivingId).ToListAsync();
                                if (infodetail.Count == 0)
                                {
                                    throw new BusException("请检查此包是否和收货单匹配");
                                }
                            }
                            List<string> infomaterlist = new List<string>();
                            var materialdata = infodetail.GroupBy(x => new { x.MaterialId, x.MaterialName }).Select(x => new { MaterialId = x.Key.MaterialId, MaterialName = x.Key.MaterialName }).ToList();
                            List<TD_RecDetail> RecDetaillist = await Db.GetIQueryable<TD_RecDetail>().Where(x => x.RecId == ReceivingId).ToListAsync();
                            //foreach (var item in materialdata)
                            //{
                            //    infomaterlist.Add(item.MaterialId);
                            //}
                            //List<PB_Material> materdatas = await Db.GetIQueryable<PB_Material>().Where(x => infomaterlist.Contains(x.Id)).ToListAsync();
                            foreach (var item in materialdata)
                            {
                                var itemdata = RecDetaillist.Where(x => x.MaterialId == item.MaterialId).FirstOrDefault();
                                if (itemdata == null)
                                {
                                    throw new BusException("请检查此包物料是否和收货单匹配");
                                }
                                var trueorfalse = await _check.GetTrueOrFalse(item.MaterialId, Locationdata.StorId, LocationId);
                                if (trueorfalse.boolType == false)
                                {
                                    throw new BusException("仓库" + item.MaterialName + "物料正在盘点中禁止上架入库");
                                }
                            }
                            if (detatildata.Count == 0)
                            {
                                //插入库存明细表
                                PB_StockLog lodata = new PB_StockLog();
                                lodata.Id = IdHelper.GetId();
                                lodata.PackId = packId;
                                lodata.StorId = Locationdata.StorId;
                                lodata.LocationId = LocationId;
                                lodata.MaterialId = "";
                                lodata.StockNumber = packdata.Nums;
                                lodata.CreatorId = _operator.UserId;
                                lodata.CreatorName = bdata.RealName;
                                lodata.OperatorId = _operator.UserId;
                                lodata.OrderID = ReceivingId;
                                lodata.CreateTime = DateTime.Now;
                                lodata.Type = 1;
                                lodata.State = 0;
                                lodata.OldOrNew = packdata.OldOrNew;
                                lodata.CirBillId = "";
                                lodata.JobId = "";
                                StockLogList.Add(lodata);
                                //List<PB_Stock> liststock = new List<PB_Stock>();
                                //List<IT_LocalDetail> listLocalDetail = new List<IT_LocalDetail>();
                                //List<IT_LocalMaterial> listLocalMaterial = new List<IT_LocalMaterial>();
                                var infolist = infodetail.GroupBy(x => new { x.MaterialId, x.OldOrNew, x.RecId }).Select(x => new { MaterialId = x.Key.MaterialId, OldOrNew = x.Key.OldOrNew, RecId = x.Key.RecId, Nums = x.Count() }).ToList();
                                foreach (var item in infolist)
                                {

                                    //插入货架上存放货物存明细表
                                    PB_Stock stockdata = new PB_Stock();
                                    stockdata.Id = IdHelper.GetId();
                                    stockdata.PackId = packId;
                                    stockdata.StorId = Locationdata.StorId;
                                    stockdata.LocationId = LocationId;
                                    stockdata.StockNumber = item.Nums;
                                    stockdata.MaterialId = item.MaterialId;
                                    stockdata.CreatorId = _operator.UserId;
                                    stockdata.CreatorName = bdata.RealName;
                                    stockdata.CreateTime = DateTime.Now;
                                    stockdata.OperatorId = _operator.UserId;
                                    stockdata.OrderID = ReceivingId;
                                    stockdata.Type = 1;
                                    stockdata.OldOrNew = packdata.OldOrNew;
                                    stockdata.CirBillId = "";
                                    stockdata.JobId = "";
                                    StockList.Add(stockdata);

                                    //收货单物料明细对应的包信息
                                    PB_UpLoadList updata = new PB_UpLoadList();
                                    updata.Id = IdHelper.GetId();
                                    updata.ParentId = ReceivingId;
                                    updata.StorId = Locationdata.StorId;
                                    updata.LocalId = LocationId;
                                    updata.PackId = packId;
                                    updata.Nums = item.Nums;
                                    updata.MaterialId = item.MaterialId;
                                    updata.CreatorId = _operator.UserId;
                                    updata.CreatorRealName = bdata.RealName;
                                    updata.CreateTime = DateTime.Now;
                                    updata.Deleted = false;
                                    updata.CirBillId = "";
                                    updata.JobId = "";
                                    UpLoadListList.Add(updata);

                                    //库存明细表
                                    IT_LocalDetail detdata = new IT_LocalDetail();
                                    detdata.Id = IdHelper.GetId();
                                    detdata.StorId = Locationdata.StorId;
                                    detdata.LocalId = LocationId;
                                    detdata.MaterialId = item.MaterialId;
                                    detdata.InTime = DateTime.Now;
                                    detdata.CreateTime = DateTime.Now;
                                    detdata.CreatorId = _operator.UserId;
                                    detdata.Deleted = false;
                                    detdata.Num = item.Nums;
                                    detdata.BarCode = data.packqrcode;
                                    detdata.PackId = packId;
                                    detdata.OldOrNew = packdata.OldOrNew;
                                    detdata.RecId = item.RecId;
                                    detdata.JobId = "";
                                    LocalDetailList.Add(detdata);

                                    //查询货架上存放货物存汇总表是否存在
                                    var materdata = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == item.MaterialId && x.StorId == Locationdata.StorId && x.LocalId == LocationId).FirstOrDefaultAsync();
                                    if (materdata == null)
                                    {
                                        //不存在新增
                                        IT_LocalMaterial itdata = new IT_LocalMaterial();
                                        itdata.Id = IdHelper.GetId();
                                        itdata.MaterialId = item.MaterialId;
                                        itdata.StorId = Locationdata.StorId;
                                        itdata.LocalId = LocationId;
                                        if (packdata.OldOrNew == 0)
                                        {
                                            itdata.Nums_O = item.Nums;
                                            itdata.Nums_N = 0;
                                        }
                                        else if (packdata.OldOrNew == 1)
                                        {
                                            itdata.Nums_O = 0;
                                            itdata.Nums_N = item.Nums;
                                        }
                                        itdata.CreatorId = _operator.UserId;
                                        itdata.CreateTime = DateTime.Now;
                                        itdata.Deleted = false;
                                        itdata.AreaId = Locationdata.AreaId;
                                        itdata.RackId = Locationdata.RackId;
                                        itdata.ScanNum = item.Nums;
                                        itdata.CheckNum = 0;
                                        LocalMaterialList.Add(itdata);
                                    }
                                    else
                                    {
                                        //存在修改

                                        if (item.OldOrNew == 0)
                                        {
                                            sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)+" + item.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + item.Nums + " where StorId='" + Locationdata.StorId + "' and LocalId='" + LocationId + "' and MaterialId='" + item.MaterialId + "'; ";
                                        }
                                        else if (item.OldOrNew == 1)
                                        {
                                            sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + item.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + item.Nums + " where StorId='" + Locationdata.StorId + "' and LocalId='" + LocationId + "' and MaterialId='" + item.MaterialId + "'; ";
                                        }
                                        //await ExecuteSqlAsync(sqlMain);
                                    }

                                    //修改物料审核前数量
                                    sqlMain += @" update PB_Material set ScanNum=IFNULL(ScanNum,0)+" + item.Nums + " where Id='" + item.MaterialId + "'; ";

                                    //修改收货单的入库数量
                                    sqlMain += @" update TD_RecDetail set InNum=IFNULL(InNum,0)+" + item.Nums + " where RecId='" + ReceivingId + "' and MaterialId='" + item.MaterialId + "'; ";
                                }
                                //await Db.InsertAsync<PB_Stock>(liststock);
                                //await Db.InsertAsync<IT_LocalDetail>(listLocalDetail);
                                //await Db.InsertAsync<IT_LocalMaterial>(listLocalMaterial);

                                //修改包的状态为已入库
                                sqlMain += @" UPDATE PB_PackList SET  Status= '3',InStorTime=NOW(),InStorUserId='" + _operator.UserId + "',InStorUserName='" + bdata.RealName + "' WHERE id='" + packId + "'; ";

                                //查询包码对应的生产任务单
                                List<PB_JobBookingQrCode> JobBookingQrCodeList = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.RecId == ReceivingId && x.PackId == packId).ToListAsync();
                                if (JobBookingQrCodeList.Count > 0)
                                {
                                    var codegroup = JobBookingQrCodeList.GroupBy(x => new { x.OrderDetailId, x.MaterialId }).Select(x => new { OrderDetailId = x.Key.OrderDetailId, MaterialId = x.Key.MaterialId, Nums = x.Count() }).ToList();
                                    if (codegroup.Count > 0)
                                    {
                                        foreach (var item in codegroup)
                                        {
                                            sqlMain += $@"  update PB_ProductionOrderDetail set CompleteNums=IFNULL(CompleteNums,0)+{item.Nums},WarehousingTime=NOW() where Id='{ item.OrderDetailId }'; ";
                                        }
                                    }
                                }

                            }
                            else
                            {
                                throw new BusException("不能重复入库");
                            }
                            //await ExecuteSqlAsync(sqlMain);
                        }
                    }
                    else
                    {
                        throw new BusException("请扫描正确的要上架的包信息");
                    }
                }
                else if (packmodel == "04")  //扫描单个物料上架
                {
                    PB_Material materdatas = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == materialId).FirstOrDefaultAsync();
                    TD_RecDetail RecDetail = await Db.GetIQueryable<TD_RecDetail>().Where(x => x.RecId == ReceivingId && x.MaterialId == materdatas.Id).FirstOrDefaultAsync();
                    //采购收货
                    if (recedata.Type == "Purchase")
                    {
                        //修改成品码对应的收货单
                        sqlMain += @" update PB_JobBookingQrCode set RecId='" + recedata.Id + "' where MaterialId='" + materialId + "' and PurchaseId='" + recedata.OrderId + "'; ";
                        string memoname = "";
                        if (noticedata.Memo.IsNullOrEmpty())
                        {
                            memoname = materdatas.Name;
                        }
                        else
                        {
                            memoname = noticedata.Memo + "," + materdatas.Name;
                        }
                        //修改入库通知单的说明字段
                        sqlMain += @" update PB_WarehousingNotice set Memo='" + memoname + "' where Id='" + recedata.RefCode + "'; ";
                    }
                    //退货收货
                    else if (recedata.Type == "ReceReturn")
                    {
                        //实例化Redis操作类
                        _redisOptions.DbChannel = (int)Redis_Type.redis6;
                        RedisSetHelper redis = new RedisSetHelper(_redisOptions);
                        PB_JobBookingQrCode jobqrcode = new PB_JobBookingQrCode();
                        jobqrcode.Id = IdHelper.GetId();
                        jobqrcode.ParentId = "";
                        jobqrcode.OrderId = "";
                        jobqrcode.OrderDetailId = "";
                        jobqrcode.MaterialId = materdatas.Id;
                        jobqrcode.MaterialName = materdatas.Name;
                        if (RedisSetHelper.Exists("QualityTestingNumber"))
                        {
                            string thedate = DateTime.Now.ToString("yyyy-MM-dd");
                            if (redis.GetString("QualityTestingTime") == thedate)
                            {
                                redis.SetString("QualityTestingNumber", (Convert.ToInt32(redis.GetString("QualityTestingNumber")) + 1).ToString());
                                jobqrcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                            }
                            else
                            {
                                redis.SetString("QualityTestingTime", thedate);
                                redis.SetString("QualityTestingNumber", "1");
                                jobqrcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                            }
                        }
                        else
                        {
                            redis.SetString("QualityTestingNumber", "0");
                        }
                        jobqrcode.QrCode = h_Material + "," + materdatas.Id;
                        jobqrcode.RecId = ReceivingId;
                        jobqrcode.OldOrNew = 1;
                        jobqrcode.PurchaseId = "";
                        jobqrcode.PackId = "";
                        JobBookingQrCode.Add(jobqrcode);
                    }

                    if (RecDetail == null)
                    {
                        throw new BusException("请检查物料是否和收货单匹配");
                    }

                    if ((RecDetail.InNum + data.Nums) > RecDetail.RecNum)
                    {
                        throw new BusException("入库数量不能大于实收数量");
                    }

                    var trueorfalse = await _check.GetTrueOrFalse(materdatas.Id, Locationdata.StorId, LocationId);
                    if (trueorfalse.boolType == false)
                    {
                        throw new BusException("仓库物料正在盘点中禁止上架入库");
                    }
                    //插入货架上存放货物存明细表
                    PB_Stock stockdata = new PB_Stock();
                    stockdata.Id = IdHelper.GetId();
                    stockdata.PackId = "";
                    stockdata.StorId = Locationdata.StorId;
                    stockdata.LocationId = LocationId;
                    stockdata.StockNumber = data.Nums;
                    stockdata.MaterialId = materialId;
                    stockdata.CreatorId = _operator.UserId;
                    stockdata.CreatorName = bdata.RealName;
                    stockdata.CreateTime = DateTime.Now;
                    stockdata.OperatorId = _operator.UserId;
                    stockdata.OrderID = ReceivingId;
                    stockdata.Type = 1;
                    stockdata.OldOrNew = 1;
                    stockdata.CirBillId = "";
                    stockdata.JobId = "";
                    StockList.Add(stockdata);

                    //插入库存明细表
                    PB_StockLog lodata = new PB_StockLog();
                    lodata.Id = IdHelper.GetId();
                    lodata.PackId = "";
                    lodata.StorId = Locationdata.StorId;
                    lodata.LocationId = LocationId;
                    lodata.MaterialId = materialId;
                    lodata.StockNumber = data.Nums;
                    lodata.CreatorId = _operator.UserId;
                    lodata.CreatorName = bdata.RealName;
                    lodata.OperatorId = _operator.UserId;
                    lodata.OrderID = ReceivingId;
                    lodata.CreateTime = DateTime.Now;
                    lodata.Type = 1;
                    lodata.State = 0;
                    lodata.OldOrNew = 1;
                    lodata.CirBillId = "";
                    lodata.JobId = "";
                    StockLogList.Add(lodata);

                    //收货单物料明细对应的包信息
                    PB_UpLoadList updata = new PB_UpLoadList();
                    updata.Id = IdHelper.GetId();
                    updata.ParentId = ReceivingId;
                    updata.StorId = Locationdata.StorId;
                    updata.LocalId = LocationId;
                    updata.PackId = "";
                    updata.MaterialId = materialId;
                    updata.Nums = data.Nums;
                    updata.CreatorId = _operator.UserId;
                    updata.CreatorRealName = bdata.RealName;
                    updata.CreateTime = DateTime.Now;
                    updata.Deleted = false;
                    updata.CirBillId = "";
                    updata.JobId = "";
                    UpLoadListList.Add(updata);

                    //库存明细表
                    IT_LocalDetail detdata = new IT_LocalDetail();
                    detdata.Id = IdHelper.GetId();
                    detdata.StorId = Locationdata.StorId;
                    detdata.LocalId = LocationId;
                    detdata.MaterialId = materialId;
                    detdata.MeasureId = materdatas.storageId;
                    detdata.InTime = DateTime.Now;
                    detdata.CreateTime = DateTime.Now;
                    detdata.CreatorId = _operator.UserId;
                    detdata.Deleted = false;
                    detdata.Num = data.Nums;
                    detdata.BarCode = data.packqrcode;
                    detdata.PackId = "";
                    detdata.Price = materdatas.Price;
                    detdata.Amount = data.Nums * materdatas.Price;
                    detdata.OldOrNew = 1;
                    detdata.RecId = ReceivingId;
                    detdata.JobId = "";
                    LocalDetailList.Add(detdata);

                    //查询货架上存放货物存汇总表是否存在
                    var materdata = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == materialId && x.StorId == Locationdata.StorId && x.LocalId == LocationId).FirstOrDefaultAsync();
                    if (materdata == null)
                    {
                        //不存在新增
                        IT_LocalMaterial itdata = new IT_LocalMaterial();
                        itdata.Id = IdHelper.GetId();
                        itdata.MaterialId = materialId;
                        itdata.StorId = Locationdata.StorId;
                        itdata.LocalId = LocationId;
                        itdata.Nums_O = 0;
                        itdata.Nums_N = Convert.ToDouble(data.Nums);
                        itdata.CreatorId = _operator.UserId;
                        itdata.CreateTime = DateTime.Now;
                        itdata.Deleted = false;
                        itdata.AreaId = Locationdata.AreaId;
                        itdata.RackId = Locationdata.RackId;
                        itdata.ScanNum = Convert.ToDouble(data.Nums);
                        itdata.CheckNum = 0;
                        LocalMaterialList.Add(itdata);
                    }
                    else
                    {
                        //存在修改
                        sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + data.Nums + ",ScanNum=IFNULL(ScanNum,0)+'" + data.Nums + "' where StorId='" + Locationdata.StorId + "' and LocalId='" + LocationId + "' and MaterialId='" + materialId + "'; ";
                    }

                    //修改物料审核前数量
                    sqlMain += @" update PB_Material set ScanNum=IFNULL(ScanNum,0)+" + data.Nums + " where Id='" + materialId + "'; ";

                    //修改收货单的入库数量
                    sqlMain += @" update TD_RecDetail set InNum=IFNULL(InNum,0)+" + data.Nums + " where RecId='" + ReceivingId + "' and MaterialId='" + materialId + "'; ";

                    //查询包码对应的生产任务单
                    List<PB_JobBookingQrCode> JobBookingQrCodeList = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.RecId == ReceivingId && x.MaterialId == materialId).ToListAsync();
                    if (JobBookingQrCodeList.Count > 0)
                    {
                        var codegroup = JobBookingQrCodeList.GroupBy(x => new { x.OrderDetailId, x.MaterialId }).Select(x => new { OrderDetailId = x.Key.OrderDetailId, MaterialId = x.Key.MaterialId, Nums = x.Count() }).ToList();
                        if (codegroup.Count > 0)
                        {
                            foreach (var item in codegroup)
                            {
                                sqlMain += $@"  update PB_ProductionOrderDetail set CompleteNums=IFNULL(CompleteNums,0)+{data.Nums},WarehousingTime=NOW() where Id='{item.OrderDetailId}'; ";
                            }
                        }
                    }

                }
                else if (packmodel == "31")
                {
                    Expression<Func<PB_CirculationBill, PB_Material, TD_RecDetail, CirBillMaterialRecDTO>> select = (a, b, c) => new CirBillMaterialRecDTO
                    {
                        CirBillId = a.Id,
                        MaterialId = a.MaterialId,
                        MaterialCode = b.Code,
                        MaterialName = b.Name,
                        MaterialSpec = b.Spec,
                        TaskDetailId = a.TaskDetailId,
                        Price = b.Price,
                        storageId = b.storageId,
                        Nums = c.RecNum,
                        RecId = c.RecId
                    };
                    select = select.BuildExtendSelectExpre();
                    var q = from a in Db.GetIQueryable<PB_CirculationBill>().AsExpandable()
                            join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                            from b in ab.DefaultIfEmpty()
                            join c in Db.GetIQueryable<TD_RecDetail>() on a.Id equals c.CirBillId into ac
                            from c in ac.DefaultIfEmpty()
                            select @select.Invoke(a, b, c);
                    var materdatas = await q.Where(x => x.CirBillId == cirbillId).FirstOrDefaultAsync();
                    TD_RecDetail RecDetail = await Db.GetIQueryable<TD_RecDetail>().Where(x => x.RecId == ReceivingId && x.MaterialId == materdatas.MaterialId && x.CirBillId == cirbillId).FirstOrDefaultAsync();
                    if (RecDetail == null)
                    {
                        throw new BusException("请检查物料是否和收货单匹配");
                    }
                    if (RecDetail.InNum > 0)
                    {
                        throw new BusException("不能重复入库");
                    }

                    var trueorfalse = await _check.GetTrueOrFalse(materdatas.MaterialId, Locationdata.StorId, LocationId);
                    if (trueorfalse.boolType == false)
                    {
                        throw new BusException("仓库物料正在盘点中禁止上架入库");
                    }
                    //插入货架上存放货物存明细表
                    PB_Stock stockdata = new PB_Stock();
                    stockdata.Id = IdHelper.GetId();
                    stockdata.PackId = "";
                    stockdata.StorId = Locationdata.StorId;
                    stockdata.LocationId = LocationId;
                    stockdata.StockNumber = materdatas.Nums;
                    stockdata.MaterialId = materdatas.MaterialId;
                    stockdata.CreatorId = _operator.UserId;
                    stockdata.CreatorName = bdata.RealName;
                    stockdata.CreateTime = DateTime.Now;
                    stockdata.OperatorId = _operator.UserId;
                    stockdata.OrderID = ReceivingId;
                    stockdata.Type = 1;
                    stockdata.OldOrNew = 1;
                    stockdata.CirBillId = cirbillId;
                    stockdata.JobId = "";
                    StockList.Add(stockdata);

                    //插入库存明细表
                    PB_StockLog lodata = new PB_StockLog();
                    lodata.Id = IdHelper.GetId();
                    lodata.PackId = "";
                    lodata.StorId = Locationdata.StorId;
                    lodata.LocationId = LocationId;
                    lodata.MaterialId = materdatas.MaterialId;
                    lodata.StockNumber = materdatas.Nums;
                    lodata.CreatorId = _operator.UserId;
                    lodata.CreatorName = bdata.RealName;
                    lodata.OperatorId = _operator.UserId;
                    lodata.OrderID = ReceivingId;
                    lodata.CreateTime = DateTime.Now;
                    lodata.Type = 1;
                    lodata.State = 0;
                    lodata.OldOrNew = 1;
                    lodata.CirBillId = cirbillId;
                    lodata.JobId = "";
                    StockLogList.Add(lodata);

                    //收货单物料明细对应的包信息
                    PB_UpLoadList updata = new PB_UpLoadList();
                    updata.Id = IdHelper.GetId();
                    updata.ParentId = ReceivingId;
                    updata.StorId = Locationdata.StorId;
                    updata.LocalId = LocationId;
                    updata.PackId = "";
                    updata.MaterialId = materdatas.MaterialId;
                    updata.Nums = materdatas.Nums;
                    updata.CreatorId = _operator.UserId;
                    updata.CreatorRealName = bdata.RealName;
                    updata.CreateTime = DateTime.Now;
                    updata.Deleted = false;
                    updata.CirBillId = cirbillId;
                    updata.JobId = "";
                    UpLoadListList.Add(updata);

                    //库存明细表
                    IT_LocalDetail detdata = new IT_LocalDetail();
                    detdata.Id = IdHelper.GetId();
                    detdata.StorId = Locationdata.StorId;
                    detdata.LocalId = LocationId;
                    detdata.MaterialId = materdatas.MaterialId;
                    detdata.MeasureId = materdatas.storageId;
                    detdata.InTime = DateTime.Now;
                    detdata.CreateTime = DateTime.Now;
                    detdata.CreatorId = _operator.UserId;
                    detdata.Deleted = false;
                    detdata.Num = materdatas.Nums;
                    detdata.BarCode = data.packqrcode;
                    detdata.PackId = "";
                    detdata.Price = materdatas.Price;
                    detdata.Amount = materdatas.Nums * materdatas.Price;
                    detdata.OldOrNew = 1;
                    detdata.RecId = ReceivingId;
                    detdata.JobId = "";
                    LocalDetailList.Add(detdata);

                    //查询货架上存放货物存汇总表是否存在
                    var materdata = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == materdatas.MaterialId && x.StorId == Locationdata.StorId && x.LocalId == LocationId).FirstOrDefaultAsync();
                    if (materdata == null)
                    {
                        //不存在新增
                        IT_LocalMaterial itdata = new IT_LocalMaterial();
                        itdata.Id = IdHelper.GetId();
                        itdata.MaterialId = materdatas.MaterialId;
                        itdata.StorId = Locationdata.StorId;
                        itdata.LocalId = LocationId;
                        itdata.Nums_O = 0;
                        itdata.Nums_N = Convert.ToDouble(materdatas.Nums);
                        itdata.CreatorId = _operator.UserId;
                        itdata.CreateTime = DateTime.Now;
                        itdata.Deleted = false;
                        itdata.AreaId = Locationdata.AreaId;
                        itdata.RackId = Locationdata.RackId;
                        itdata.ScanNum = Convert.ToDouble(materdatas.Nums);
                        itdata.CheckNum = 0;
                        LocalMaterialList.Add(itdata);
                    }
                    else
                    {
                        //存在修改
                        sqlMain += @"update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + materdatas.Nums + ",ScanNum=IFNULL(ScanNum,0)+'" + materdatas.Nums + "' where StorId='" + Locationdata.StorId + "' and LocalId='" + LocationId + "' and MaterialId='" + materdatas.MaterialId + "'; ";
                    }

                    //修改物料审核前数量
                    sqlMain += @" update PB_Material set ScanNum=IFNULL(ScanNum,0)+" + materdatas.Nums + " where Id='" + materdatas.MaterialId + "'; ";
                    //修改收货单的入库数量
                    sqlMain += @" update TD_RecDetail set InNum=IFNULL(InNum,0)+" + materdatas.Nums + " where RecId='" + ReceivingId + "' and MaterialId='" + materdatas.MaterialId + "' and CirBillId='" + cirbillId + "'; ";

                    if (!materdatas.IsNullOrEmpty())
                    {
                        sqlMain += $@" update PB_ProductionOrderDetail set CompleteNums=IFNULL(CompleteNums,0)+{materdatas.Nums},WarehousingTime=NOW() where Id='{ materdatas.TaskDetailId }'; ";
                    }

                }
                else if (packmodel == "14")
                {
                    //查询成品信息
                    PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == JobId).FirstOrDefaultAsync();
                    if (jobdata.IsNullOrEmpty())
                    {
                        throw new BusException("成品码已作废,请做补码处理");
                    }
                    if (jobdata.PackStatus == 1)
                    {
                        throw new BusException("成品码已作废,请做补码处理");
                    }
                    //查询成品物料与收货单物料是否匹配
                    TD_RecDetail RecDetail = await Db.GetIQueryable<TD_RecDetail>().Where(x => x.RecId == ReceivingId && x.MaterialId == jobdata.MaterialId).FirstOrDefaultAsync();
                    if (jobdata != null)
                    {
                        if (recedata.Type == "ReceReturn")
                        {
                            //修改单个成品对应的收货单
                            sqlMain += @" update PB_JobBookingQrCode set RecId='" + ReceivingId + "' where Id='" + JobId + "'; ";
                            //添加单个成品的入库通知
                            sqlMain += @" INSERT INTO PB_JobNotice(Id,JobId,NoticeId,RecId,CreatorId,CreateTime,Deleted) values ('" + IdHelper.GetId() + "','" + JobId + "','" + recedata.RefCode + "','" + ReceivingId + "','" + _operator.UserId + "',NOW(),0); ";
                        }
                        else
                        {
                            PB_JobNotice notice = await Db.GetIQueryable<PB_JobNotice>().Where(x => x.JobId == JobId && x.RecId == ReceivingId).FirstOrDefaultAsync();
                            if (notice == null)
                            {
                                throw new BusException("未通知入库的成品不能扫码上架");
                            }
                        }
                        IT_LocalDetail LocalDetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.JobId == JobId).FirstOrDefaultAsync();
                        if (LocalDetail != null)
                        {
                            throw new BusException("已入库不能重复入库");
                        }
                        if (!jobdata.PackId.IsNullOrEmpty())
                        {
                            throw new BusException("已打包的成品不能按单个成品入库");
                        }
                        if (RecDetail == null)
                        {
                            throw new BusException("请检查物料是否和收货单匹配");
                        }
                        if ((RecDetail.InNum + 1) > RecDetail.RecNum)
                        {
                            throw new BusException("入库数量不能大于收货数量");
                        }
                        var trueorfalse = await _check.GetTrueOrFalse(jobdata.MaterialId, Locationdata.StorId, LocationId);
                        if (trueorfalse.boolType == false)
                        {
                            throw new BusException("仓库物料正在盘点中禁止上架入库");
                        }
                        //插入货架上存放货物存明细表
                        PB_Stock stockdata = new PB_Stock();
                        stockdata.Id = IdHelper.GetId();
                        stockdata.PackId = "";
                        stockdata.StorId = Locationdata.StorId;
                        stockdata.LocationId = LocationId;
                        stockdata.StockNumber = 1;
                        stockdata.MaterialId = jobdata.MaterialId;
                        stockdata.CreatorId = _operator.UserId;
                        stockdata.CreatorName = bdata.RealName;
                        stockdata.CreateTime = DateTime.Now;
                        stockdata.OperatorId = _operator.UserId;
                        stockdata.OrderID = ReceivingId;
                        stockdata.Type = 1;
                        stockdata.OldOrNew = jobdata.OldOrNew;
                        stockdata.CirBillId = "";
                        stockdata.JobId = JobId;
                        StockList.Add(stockdata);

                        //插入库存明细表
                        PB_StockLog lodata = new PB_StockLog();
                        lodata.Id = IdHelper.GetId();
                        lodata.PackId = "";
                        lodata.StorId = Locationdata.StorId;
                        lodata.LocationId = LocationId;
                        lodata.MaterialId = jobdata.MaterialId;
                        lodata.StockNumber = 1;
                        lodata.CreatorId = _operator.UserId;
                        lodata.CreatorName = bdata.RealName;
                        lodata.OperatorId = _operator.UserId;
                        lodata.OrderID = ReceivingId;
                        lodata.CreateTime = DateTime.Now;
                        lodata.Type = 1;
                        lodata.State = 0;
                        lodata.OldOrNew = jobdata.OldOrNew;
                        lodata.CirBillId = "";
                        lodata.JobId = JobId;
                        StockLogList.Add(lodata);

                        //收货单物料明细对应的包信息
                        PB_UpLoadList updata = new PB_UpLoadList();
                        updata.Id = IdHelper.GetId();
                        updata.ParentId = ReceivingId;
                        updata.StorId = Locationdata.StorId;
                        updata.LocalId = LocationId;
                        updata.PackId = "";
                        updata.MaterialId = jobdata.MaterialId;
                        updata.Nums = 1;
                        updata.CreatorId = _operator.UserId;
                        updata.CreatorRealName = bdata.RealName;
                        updata.CreateTime = DateTime.Now;
                        updata.Deleted = false;
                        updata.CirBillId = "";
                        updata.JobId = JobId;
                        UpLoadListList.Add(updata);

                        PB_Material materdatas = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == jobdata.MaterialId).FirstOrDefaultAsync();

                        //库存明细表
                        IT_LocalDetail detdata = new IT_LocalDetail();
                        detdata.Id = IdHelper.GetId();
                        detdata.StorId = Locationdata.StorId;
                        detdata.LocalId = LocationId;
                        detdata.MaterialId = jobdata.MaterialId;
                        detdata.MeasureId = materdatas.storageId;
                        detdata.InTime = DateTime.Now;
                        detdata.CreateTime = DateTime.Now;
                        detdata.CreatorId = _operator.UserId;
                        detdata.Deleted = false;
                        detdata.Num = 1;
                        detdata.BarCode = data.packqrcode;
                        detdata.PackId = "";
                        detdata.Price = materdatas.Price;
                        detdata.Amount = materdatas.Price;
                        detdata.OldOrNew = jobdata.OldOrNew;
                        detdata.RecId = ReceivingId;
                        detdata.JobId = JobId;
                        LocalDetailList.Add(detdata);

                        //查询货架上存放货物存汇总表是否存在
                        var materdata = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == jobdata.MaterialId && x.StorId == Locationdata.StorId && x.LocalId == LocationId).FirstOrDefaultAsync();
                        if (materdata == null)
                        {
                            if (jobdata.OldOrNew == 0)
                            {
                                //不存在新增
                                IT_LocalMaterial itdata = new IT_LocalMaterial();
                                itdata.Id = IdHelper.GetId();
                                itdata.MaterialId = jobdata.MaterialId;
                                itdata.StorId = Locationdata.StorId;
                                itdata.LocalId = LocationId;
                                itdata.Nums_O = 1;
                                itdata.Nums_N = 0;
                                itdata.CreatorId = _operator.UserId;
                                itdata.CreateTime = DateTime.Now;
                                itdata.Deleted = false;
                                itdata.AreaId = Locationdata.AreaId;
                                itdata.RackId = Locationdata.RackId;
                                itdata.ScanNum = 1;
                                itdata.CheckNum = 0;
                                LocalMaterialList.Add(itdata);
                            }
                            else if (jobdata.OldOrNew == 1)
                            {
                                //不存在新增
                                IT_LocalMaterial itdata = new IT_LocalMaterial();
                                itdata.Id = IdHelper.GetId();
                                itdata.MaterialId = jobdata.MaterialId;
                                itdata.StorId = Locationdata.StorId;
                                itdata.LocalId = LocationId;
                                itdata.Nums_O = 0;
                                itdata.Nums_N = 1;
                                itdata.CreatorId = _operator.UserId;
                                itdata.CreateTime = DateTime.Now;
                                itdata.Deleted = false;
                                itdata.AreaId = Locationdata.AreaId;
                                itdata.RackId = Locationdata.RackId;
                                itdata.ScanNum = 1;
                                itdata.CheckNum = 0;
                                LocalMaterialList.Add(itdata);
                            }
                        }
                        else
                        {
                            //存在修改
                            if (jobdata.OldOrNew == 0)
                            {
                                sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_O,0)+1,ScanNum=IFNULL(ScanNum,0)+1 where StorId='" + Locationdata.StorId + "' and LocalId='" + LocationId + "' and MaterialId='" + jobdata.MaterialId + "'; ";
                            }
                            else if (jobdata.OldOrNew == 1)
                            {
                                sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+1,ScanNum=IFNULL(ScanNum,0)+1 where StorId='" + Locationdata.StorId + "' and LocalId='" + LocationId + "' and MaterialId='" + jobdata.MaterialId + "'; ";
                            }
                        }

                        //修改物料审核前数量
                        sqlMain += @" update PB_Material set ScanNum=IFNULL(ScanNum,0)+1 where Id='" + jobdata.MaterialId + "'; ";

                        //修改收货单的入库数量
                        sqlMain += @" update TD_RecDetail set InNum=IFNULL(InNum,0)+1 where RecId='" + ReceivingId + "' and MaterialId='" + jobdata.MaterialId + "'; ";

                        //查询包码对应的生产任务单
                        List<PB_JobBookingQrCode> JobBookingQrCodeList = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.RecId == ReceivingId && x.Id == JobId).ToListAsync();
                        if (JobBookingQrCodeList.Count > 0)
                        {
                            var codegroup = JobBookingQrCodeList.GroupBy(x => new { x.OrderDetailId, x.MaterialId }).Select(x => new { OrderDetailId = x.Key.OrderDetailId, MaterialId = x.Key.MaterialId, Nums = x.Count() }).ToList();
                            if (codegroup.Count > 0)
                            {
                                foreach (var item in codegroup)
                                {
                                    sqlMain += $@"  update PB_ProductionOrderDetail set CompleteNums=IFNULL(CompleteNums,0)+{item.Nums},WarehousingTime=NOW() where Id='{ item.OrderDetailId }'; ";
                                }
                            }
                        }

                    }
                    else
                    {
                        throw new BusException("请扫描正确的成品二维码");
                    }
                }

                await Db.InsertAsync<PB_Stock>(StockList);
                await Db.InsertAsync<PB_StockLog>(StockLogList);
                await Db.InsertAsync<PB_UpLoadList>(UpLoadListList);
                await Db.InsertAsync<IT_LocalDetail>(LocalDetailList);
                await Db.InsertAsync<IT_LocalMaterial>(LocalMaterialList);
                await Db.InsertAsync<PB_JobBookingQrCode>(JobBookingQrCode);
                await ExecuteSqlAsync(sqlMain);
            }
            else
            {
                throw new BusException("请扫描正确的收货单二维码");
            }
        }

        /// <summary>
        /// 删除已入库的包信息
        /// </summary>
        /// <param name="receivingId">收货单id</param>
        /// <param name="data">库存包信息</param>
        /// <returns></returns>
        [Transactional]
        public async Task DeleteStockDataAsync(string receivingId, PB_UpLoadListDataDTO data)
        {
            string sqlMain = string.Empty;
            //删除的是否是包
            if (!data.PackId.IsNullOrEmpty())
            {
                PB_PackList packdata = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == data.PackId).FirstOrDefaultAsync();
                PB_UpLoadList UpLoadList = await Db.GetIQueryable<PB_UpLoadList>().Where(x => x.ParentId == receivingId && x.PackId == data.PackId).FirstOrDefaultAsync();
                if (UpLoadList == null)
                {
                    throw new BusException("已移除不能重复移除");
                }

                //标准包
                if (packdata.PackageType == 0)
                {
                    //删除PB_Stock表信息
                    sqlMain = @" delete from PB_Stock where PackId='" + data.PackId + "' and OrderID='" + receivingId + "'; ";
                    //删除PB_StockLog表信息
                    sqlMain += @" delete from PB_StockLog where PackId='" + data.PackId + "' and OrderID='" + receivingId + "'; ";
                    //收货单物料明细对应的包信息日志
                    sqlMain += @" delete from PB_UpLoadList where PackId='" + data.PackId + "' and ParentId='" + receivingId + "'; ";
                    //删除库存明细
                    sqlMain += @" DELETE from IT_LocalDetail where PackId='" + data.PackId + "'and StorId='" + data.StorId + "' and LocalId='" + data.LocationId + "'; ";
                    //修改包的状态为已通知入库
                    sqlMain += @" UPDATE PB_PackList SET  Status= '2',InStorTime=NULL,InStorUserId=NULL,InStorUserName=NULL  WHERE id='" + data.PackId + "'; ";
                    //修改物料的审核前数量
                    sqlMain += @" update PB_Material set ScanNum=IFNULL(ScanNum,0)-" + data.StockNumber + " where Id='" + data.MaterialId + "'; ";
                    //删除库存汇总
                    if (data.OldOrNew == 0)
                    {
                        sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + data.StockNumber + ",ScanNum=IFNULL(ScanNum,0)-" + data.StockNumber + " where MaterialId='" + data.MaterialId + "' and StorId='" + data.StorId + "' and LocalId='" + data.LocationId + "'; ";
                    }
                    else if (data.OldOrNew == 1)
                    {
                        sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + data.StockNumber + ",ScanNum=IFNULL(ScanNum,0)-" + data.StockNumber + " where MaterialId='" + data.MaterialId + "' and StorId='" + data.StorId + "' and LocalId='" + data.LocationId + "'; ";
                    }
                    sqlMain += @" update TD_RecDetail set InNum=IFNULL(InNum,0)-" + data.StockNumber + " where RecId='" + receivingId + "' and MaterialId='" + data.MaterialId + "'; ";
                    //查询包码对应的生产任务单
                    List<PB_JobBookingQrCode> JobBookingQrCodeList = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.RecId == receivingId && x.PackId == data.PackId).ToListAsync();
                    if (JobBookingQrCodeList.Count > 0)
                    {
                        var codegroup = JobBookingQrCodeList.GroupBy(x => new { x.OrderDetailId, x.MaterialId }).Select(x => new { OrderDetailId = x.Key.OrderDetailId, MaterialId = x.Key.MaterialId, Nums = x.Count() }).ToList();
                        if (codegroup.Count > 0)
                        {
                            foreach (var item in codegroup)
                            {
                                sqlMain += $@"  update PB_ProductionOrderDetail set CompleteNums=IFNULL(CompleteNums,0)-{item.Nums},WarehousingTime=NOW() where Id='{ item.OrderDetailId }'; ";
                            }
                        }
                    }
                }
                else if (packdata.PackageType == 1)  //混合包
                {
                    //删除PB_Stock表信息
                    sqlMain = @" delete from PB_Stock where PackId='" + data.PackId + "' and OrderID='" + receivingId + "'; ";
                    //删除PB_StockLog表信息
                    sqlMain += @" delete from PB_StockLog where PackId='" + data.PackId + "' and OrderID='" + receivingId + "'; ";
                    //收货单物料明细对应的包信息日志
                    sqlMain += @" delete from PB_UpLoadList where PackId='" + data.PackId + "' and ParentId='" + receivingId + "'; ";
                    //删除库存明细
                    sqlMain += @" DELETE from IT_LocalDetail where PackId='" + data.PackId + "'and StorId='" + data.StorId + "' and LocalId='" + data.LocationId + "'; ";
                    //修改包的状态为已通知入库
                    sqlMain += @" UPDATE PB_PackList SET  Status= '2',InStorTime=NULL,InStorUserId=NULL,InStorUserName=NULL WHERE id='" + data.PackId + "'; ";
                    //修改物料的审核前数量
                    sqlMain += @" update PB_Material set ScanNum=IFNULL(ScanNum,0)-" + data.StockNumber + " where Id='" + data.MaterialId + "'; ";
                    List<IT_LocalDetail> LocalDetailList = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.PackId == data.PackId).ToListAsync();
                    foreach (var item in LocalDetailList)
                    {
                        //删除库存汇总
                        if (data.OldOrNew == 0)
                        {
                            sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where MaterialId='" + item.MaterialId + "' and StorId='" + data.StorId + "' and LocalId='" + data.LocationId + "'; ";
                        }
                        else if (data.OldOrNew == 1)
                        {
                            sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where MaterialId='" + item.MaterialId + "' and StorId='" + data.StorId + "' and LocalId='" + data.LocationId + "'; ";
                        }
                        sqlMain += @" update TD_RecDetail set InNum=IFNULL(InNum,0)-" + item.Num + " where RecId='" + receivingId + "' and MaterialId='" + item.MaterialId + "'; ";
                    }
                    //查询包码对应的生产任务单
                    List<PB_JobBookingQrCode> JobBookingQrCodeList = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.RecId == receivingId && x.PackId == data.PackId).ToListAsync();
                    if (JobBookingQrCodeList.Count > 0)
                    {
                        var codegroup = JobBookingQrCodeList.GroupBy(x => new { x.OrderDetailId, x.MaterialId }).Select(x => new { OrderDetailId = x.Key.OrderDetailId, MaterialId = x.Key.MaterialId, Nums = x.Count() }).ToList();
                        if (codegroup.Count > 0)
                        {
                            foreach (var item in codegroup)
                            {
                                sqlMain += $@"  update PB_ProductionOrderDetail set CompleteNums=IFNULL(CompleteNums,0)-{item.Nums},WarehousingTime=NOW() where Id='{ item.OrderDetailId }'; ";
                            }
                        }
                    }
                }
            }
            else //删除的是否为单个物料或半成品(流转单物料)
            {
                if (!data.CirBillId.IsNullOrEmpty())
                {
                    PB_UpLoadList UpLoadList = await Db.GetIQueryable<PB_UpLoadList>().Where(x => x.ParentId == receivingId && x.CirBillId == data.CirBillId).FirstOrDefaultAsync();
                    if (UpLoadList == null)
                    {
                        throw new BusException("已移除不能重复移除");
                    }
                    //删除PB_Stock表信息
                    sqlMain = @" delete from PB_Stock where MaterialId='" + data.MaterialId + "' and OrderID='" + receivingId + "' and LocationId='" + data.LocationId + "' and StockNumber='" + data.StockNumber + "' and CirBillId='" + data.CirBillId + "'  LIMIT 1; ";
                    //删除PB_StockLog表信息
                    sqlMain += @" delete from PB_StockLog where MaterialId='" + data.MaterialId + "' and OrderID='" + receivingId + "'  and LocationId='" + data.LocationId + "' and StockNumber='" + data.StockNumber + "' and CirBillId='" + data.CirBillId + "'  LIMIT 1;  ";
                    //收货单物料明细对应的包信息日志
                    sqlMain += @" delete from PB_UpLoadList where MaterialId='" + data.MaterialId + "' and Id='" + data.Id + "' and CirBillId='" + data.CirBillId + "'; ";
                    sqlMain += @" update TD_RecDetail set InNum=IFNULL(InNum,0)-" + data.StockNumber + " where RecId='" + receivingId + "' and MaterialId='" + data.MaterialId + "' and CirBillId='" + data.CirBillId + "'; ";
                    //删除库存明细
                    sqlMain += @" DELETE from IT_LocalDetail where  MaterialId='" + data.MaterialId + "' and RecId='" + receivingId + "' and StorId='" + data.StorId + "' and LocalId='" + data.LocationId + "' and Num='" + data.StockNumber + "'  LIMIT 1; ";
                }
                else if (!data.JobId.IsNullOrEmpty())
                {
                    PB_UpLoadList UpLoadList = await Db.GetIQueryable<PB_UpLoadList>().Where(x => x.ParentId == receivingId && x.JobId == data.JobId).FirstOrDefaultAsync();
                    if (UpLoadList == null)
                    {
                        throw new BusException("已移除不能重复移除");
                    }
                    //删除PB_Stock表信息
                    sqlMain = @" delete from PB_Stock where MaterialId='" + data.MaterialId + "' and OrderID='" + receivingId + "' and LocationId='" + data.LocationId + "' and StockNumber='" + data.StockNumber + "' and JobId='" + data.JobId + "'  LIMIT 1; ";
                    //删除PB_StockLog表信息
                    sqlMain += @" delete from PB_StockLog where MaterialId='" + data.MaterialId + "' and OrderID='" + receivingId + "'  and LocationId='" + data.LocationId + "' and StockNumber='" + data.StockNumber + "' and JobId='" + data.JobId + "'  LIMIT 1;  ";
                    //收货单物料明细对应的包信息日志
                    sqlMain += @" delete from PB_UpLoadList where MaterialId='" + data.MaterialId + "' and Id='" + data.Id + "' and JobId='" + data.JobId + "'; ";
                    sqlMain += @" update TD_RecDetail set InNum=IFNULL(InNum,0)-" + data.StockNumber + " where RecId='" + receivingId + "' and MaterialId='" + data.MaterialId + "'; ";
                    //删除库存明细
                    sqlMain += @" DELETE from IT_LocalDetail where  JobId='" + data.JobId + "'; ";
                    //查询包码对应的生产任务单
                    PB_JobBookingQrCode JobBookingQrCodeList = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.RecId == receivingId && x.Id == data.JobId).FirstOrDefaultAsync();
                    if (!JobBookingQrCodeList.IsNullOrEmpty())
                    {
                        sqlMain += $@"  update PB_ProductionOrderDetail set CompleteNums=IFNULL(CompleteNums,0)-1 where Id='{ JobBookingQrCodeList.OrderDetailId }'; ";
                    }
                }
                else
                {
                    PB_UpLoadList UpLoadList = await Db.GetIQueryable<PB_UpLoadList>().Where(x => x.ParentId == receivingId && x.MaterialId == data.MaterialId && x.PackId == "" && x.JobId == "" && x.CirBillId == "" && x.Nums == data.StockNumber).FirstOrDefaultAsync();
                    if (UpLoadList == null)
                    {
                        throw new BusException("已移除不能重复移除");
                    }
                    sqlMain = @" update TD_RecDetail set InNum=IFNULL(InNum,0)-" + data.StockNumber + " where RecId='" + receivingId + "' and MaterialId='" + data.MaterialId + "'; ";
                    //删除PB_Stock表信息
                    sqlMain += @" delete from PB_Stock where MaterialId='" + data.MaterialId + "' and OrderID='" + receivingId + "' and LocationId='" + data.LocationId + "' and StockNumber='" + data.StockNumber + "'  LIMIT 1; ";
                    //删除PB_StockLog表信息
                    sqlMain += @" delete from PB_StockLog where MaterialId='" + data.MaterialId + "' and OrderID='" + receivingId + "'  and LocationId='" + data.LocationId + "' and StockNumber='" + data.StockNumber + "'  LIMIT 1;  ";
                    //收货单物料明细对应的包信息日志
                    sqlMain += @" delete from PB_UpLoadList where MaterialId='" + data.MaterialId + "' and Id='" + data.Id + "'; ";
                    //删除库存明细
                    sqlMain += @" DELETE from IT_LocalDetail where  MaterialId='" + data.MaterialId + "' and RecId='" + receivingId + "' and StorId='" + data.StorId + "' and LocalId='" + data.LocationId + "' and Num='" + data.StockNumber + "'  LIMIT 1; ";

                    //查询包码对应的生产任务单
                    List<PB_JobBookingQrCode> JobBookingQrCodeList = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.RecId == receivingId && x.MaterialId == data.MaterialId).ToListAsync();
                    if (JobBookingQrCodeList.Count > 0)
                    {
                        var codegroup = JobBookingQrCodeList.GroupBy(x => new { x.OrderDetailId, x.MaterialId }).Select(x => new { OrderDetailId = x.Key.OrderDetailId, MaterialId = x.Key.MaterialId, Nums = x.Count() }).ToList();
                        if (codegroup.Count > 0)
                        {
                            foreach (var item in codegroup)
                            {
                                sqlMain += $@"  update PB_ProductionOrderDetail set CompleteNums=IFNULL(CompleteNums,0)-{data.StockNumber} where Id='{ item.OrderDetailId }'; ";
                            }
                        }
                    }

                }

                
                //修改物料的审核前数量
                sqlMain += @" update PB_Material set ScanNum=IFNULL(ScanNum,0)-" + data.StockNumber + " where Id='" + data.MaterialId + "'; ";
                //删除库存汇总
                if (data.OldOrNew == 0)
                {
                    sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + data.StockNumber + ",ScanNum=IFNULL(ScanNum,0)-" + data.StockNumber + " where MaterialId='" + data.MaterialId + "' and StorId='" + data.StorId + "' and LocalId='" + data.LocationId + "'; ";
                }
                else if (data.OldOrNew == 1)
                {
                    sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + data.StockNumber + ",ScanNum=IFNULL(ScanNum,0)-" + data.StockNumber + " where MaterialId='" + data.MaterialId + "' and StorId='" + data.StorId + "' and LocalId='" + data.LocationId + "'; ";
                }
                
            }
            await ExecuteSqlAsync(sqlMain);
        }

        /// <summary>
        /// 开始作业
        /// </summary>
        /// <param name="idIn">收货单Id</param>
        /// 增加打码判断  2022-02-21   赵锦涛
        /// 
        /// <returns></returns>
        [Transactional]
        public async Task<AjaxResult> SaveStartJob(string idIn)
        {
            Base_User bdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            TD_Receiving recedata = await Db.GetIQueryable<TD_Receiving>().Where(x => x.Id == idIn).FirstOrDefaultAsync();
            //收货单类型为成品收货、原材新品收货、五金收货、外协半成品收货、回货收货
            if (recedata.Type == "Product" || recedata.Type== "RawMaterial" || recedata.Type == "Hardware" || recedata.Type == "HalfProduct" )
            {
                Expression<Func<PB_JobBookingQrCode, PB_PackListInfo, PB_PackList, PB_Material, TD_ReceivingJobCodeDTO>> select = (a, b, c, d) => new TD_ReceivingJobCodeDTO
                {
                    Id = a.Id,
                    MaterialId = a.MaterialId,
                    RecId = a.RecId,
                    PackId = c.Id,
                    BoxName = c.BoxName,
                    MaterialName = d.Name
                };
                select = select.BuildExtendSelectExpre();
                var q = from a in Db.GetIQueryable<PB_JobBookingQrCode>().AsExpandable()
                        join b in Db.GetIQueryable<PB_PackListInfo>() on a.Id equals b.JobBookingId into ab
                        from b in ab.DefaultIfEmpty()
                        join c in Db.GetIQueryable<PB_PackList>() on b.PackId equals c.Id into ac
                        from c in ac.DefaultIfEmpty()
                        join d in Db.GetIQueryable<PB_Material>() on a.MaterialId equals d.Id into ad
                        from d in ad.DefaultIfEmpty()
                        select @select.Invoke(a, b, c, d);
                var resdata = await q.Where(x => x.RecId == idIn).ToListAsync();
                var packdatalist = resdata.GroupBy(x => new { x.PackId }).Select(x => new { PackId = x.Key.PackId }).Where(x => x.PackId != null).ToList();

                Expression<Func<TD_RecDetail, PB_Material, TD_RecDetailPrintDTO>> selectd = (a, b) => new TD_RecDetailPrintDTO
                {
                    Id = a.Id,
                    MaterialId = a.MaterialId,
                    RecId = a.RecId,
                    IsSingle = b.IsSingle,
                    MaterialName = b.Name
                };
                selectd = selectd.BuildExtendSelectExpre();
                var qdata = from a in Db.GetIQueryable<TD_RecDetail>().AsExpandable()
                            join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                            from b in ab.DefaultIfEmpty()
                            select @selectd.Invoke(a, b);
                var Materiallist = await qdata.Where(x => x.RecId == idIn).ToListAsync();
                //Expression<Func<PB_PackList, PB_PackListInfo, PB_JobBookingQrCode, PB_Material, PB_MaterialType, TD_ReceivingPackDTO>> select = (a, b, c, d, e) => new TD_ReceivingPackDTO
                //{
                //    Id = a.Id,
                //    BoxName = a.BoxName,
                //    MaterialId = a.MaterialId,
                //    MaterialName = d.Name,
                //    MaterialTypeName = e.Name,
                //    QrCode = a.QrCode,
                //    RecId = c.RecId
                //};
                //select = select.BuildExtendSelectExpre();
                //var q = from a in Db.GetIQueryable<PB_PackList>().AsExpandable()
                //        join b in Db.GetIQueryable<PB_PackListInfo>() on a.Id equals b.PackId into ab
                //        from b in ab.DefaultIfEmpty()
                //        join c in Db.GetIQueryable<PB_JobBookingQrCode>() on b.JobBookingId equals c.Id into ac
                //        from c in ac.DefaultIfEmpty()
                //        join d in Db.GetIQueryable<PB_Material>() on a.MaterialId equals d.Id into ad
                //        from d in ad.DefaultIfEmpty()
                //        join e in Db.GetIQueryable<PB_MaterialType>() on d.MaterialTypeId equals e.Id into ae
                //        from e in ae.DefaultIfEmpty()
                //        select @select.Invoke(a, b, c, d, e);
                //var resdata = await q.Where(x => x.RecId == idIn).ToListAsync();
                if (resdata.Count == 0)
                {
                    throw new BusException("请先进行打码");
                }
                else
                {
                    var Singledata = Materiallist.Where(x => x.IsSingle == true).ToList();
                    if (Singledata.Count != Materiallist.Count)
                    {
                        if (packdatalist.Count == 0)
                        {
                            throw new BusException("请先进行物料打包");
                        }
                    }
                }
                var packdata = resdata.GroupBy(x => new { x.MaterialId, x.PackId, x.BoxName, x.MaterialName }).Select(x => new
                {
                    BoxName = x.Key.BoxName,
                    MaterialId = x.Key.MaterialId,
                    PackId = x.Key.PackId,
                    MaterialName = x.Key.MaterialName
                }).ToList();
                string dataId = IdHelper.GetId();
                string memo = string.Empty;
                if (packdata.Count > 0)
                {
                    string sqlMain = string.Empty;
                    foreach (var item in packdata)
                    {
                        sqlMain += @" update PB_PackList set NoticeId='" + dataId + "',Status=2 where Id='" + item.PackId + "'; ";
                        if (!item.BoxName.IsNullOrEmpty())
                        {
                            memo += item.BoxName + ",";
                        }
                        else
                        {
                            memo += item.MaterialName + ",";
                        }
                    }
                    if (memo.Length > 0)
                    {
                        memo = memo.Substring(0, memo.Length - 1);
                    }
                    await ExecuteSqlAsync(sqlMain);
                }
                int Return = 0;
                string sqlstr = "UPDATE  TD_Receiving set Status=3,RefCode='" + dataId + "',  UpdateTime=NOW()  where Id='" + idIn + "';";
                Return = await ExecuteSqlAsync(sqlstr);
                if (Return > 0)
                {
                    PB_WarehousingNotice pB_WarehousingNotice = new PB_WarehousingNotice();
                    pB_WarehousingNotice.Id = dataId;
                    pB_WarehousingNotice.QrCode = h_WarehousingNotice + "," + dataId;
                    pB_WarehousingNotice.DeptId = bdata.DepartmentId;
                    pB_WarehousingNotice.CreatorName = bdata.RealName;
                    pB_WarehousingNotice.CreateTime = DateTime.Now;
                    pB_WarehousingNotice.CreatorId = _operator.UserId;
                    pB_WarehousingNotice.Deleted = false;
                    pB_WarehousingNotice.Type = 1;
                    pB_WarehousingNotice.CustomerToexamine = 1;
                    pB_WarehousingNotice.Memo = memo;
                    pB_WarehousingNotice.StorId = recedata.StorId;
                    await Db.InsertAsync<PB_WarehousingNotice>(pB_WarehousingNotice);
                    AjaxResult res = new AjaxResult
                    {
                        Success = true,
                        Msg = "请求成功！"
                    };

                    return res;
                }
                else
                {
                    AjaxResult res = new AjaxResult
                    {
                        Success = false,
                        Msg = "提交数据有误！"
                    };

                    return res;
                }
            }
            else 
            {
                string remaks = string.Empty;
                //入库通知单Id
                string dataId = IdHelper.GetId();
                //修改收货单状态为开始作业
                string sqlstr = "UPDATE  TD_Receiving set Status=3,RefCode='" + dataId + "',  UpdateTime=NOW()  where Id='" + idIn + "';";
                Expression<Func<TD_RecDetail, PB_Material, TD_RecDetailPrintDTO>> selectd = (a, b) => new TD_RecDetailPrintDTO
                {
                    Id = a.Id,
                    MaterialId = a.MaterialId,
                    RecId = a.RecId,
                    IsSingle = b.IsSingle,
                    MaterialName = b.Name
                };
                selectd = selectd.BuildExtendSelectExpre();
                var qdata = from a in Db.GetIQueryable<TD_RecDetail>().AsExpandable()
                            join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                            from b in ab.DefaultIfEmpty()
                            select @selectd.Invoke(a, b);
                var Materiallist = await qdata.Where(x => x.RecId == idIn).ToListAsync();
                foreach (var item in Materiallist) {

                    remaks += item.MaterialName + ",";
                
          
                if (remaks.Length > 0)
                {
                    remaks = remaks.Substring(0, remaks.Length - 1);
                }
            }
                int Return = await ExecuteSqlAsync(sqlstr);
                if (Return > 0)
                {
                    //生成入库通知单
                    PB_WarehousingNotice pB_WarehousingNotice = new PB_WarehousingNotice();
                    pB_WarehousingNotice.Id = dataId;
                    pB_WarehousingNotice.QrCode = h_WarehousingNotice + "," + dataId;
                    pB_WarehousingNotice.DeptId = bdata.DepartmentId;
                    pB_WarehousingNotice.CreatorName = bdata.RealName;
                    pB_WarehousingNotice.CreateTime = DateTime.Now;
                    pB_WarehousingNotice.CreatorId = _operator.UserId;
                    pB_WarehousingNotice.Deleted = false;
                    pB_WarehousingNotice.Type = 1;
                    pB_WarehousingNotice.CustomerToexamine = 1;
                    pB_WarehousingNotice.Memo = remaks;
                    pB_WarehousingNotice.StorId = recedata.StorId;
                    await Db.InsertAsync<PB_WarehousingNotice>(pB_WarehousingNotice);
                    AjaxResult res = new AjaxResult
                    {
                        Success = true,
                        Msg = "请求成功！"
                    };
                    return res;
                }
                else
                {
                    AjaxResult res = new AjaxResult
                    {
                        Success = false,
                        Msg = "提交数据有误！"
                    };

                    return res;
                }
            }
        }

        public async Task<AjaxResult> SaveToExamine(QuerServeTOExamineDTO queryTable)
        {
            int Return = 0;
            if (queryTable.judge)
            {
                string Updatesql = "";
                for (int i = 0; i < queryTable.MaterialList.Count; i++)
                {
                    Updatesql += " UPDATE TD_RecDetail SET RecNum='"+ queryTable.MaterialList[i].RecNum + "' WHERE RecId='" + queryTable.idIn + "' AND MaterialId='" + queryTable.MaterialList[i].MaterialId + "';";

                }
                var packdata = await Db.GetIQueryable<TD_Receiving>().Where(x => x.Id == queryTable.idIn).FirstOrDefaultAsync();
                string sqlstr = " UPDATE  TD_Receiving set Status=1 ,UpdateTime=NOW()  where Id='" + queryTable.idIn + "';";
                Return = await ExecuteSqlAsync(Updatesql+sqlstr);
            }
            else
            {
                Return = await ExecuteSqlAsync("UPDATE TD_Receiving  set Status=2 ,UpdateTime=NOW()  where Id='" + queryTable.idIn + "' ");
            }
            if (Return > 0)
            {
                AjaxResult res = new AjaxResult
                {
                    Success = true,
                    Msg = "请求成功！"
                };

                return res;
            }
            else
            {
                AjaxResult res = new AjaxResult
                {
                    Success = false,
                    Msg = "提交数据有误！"
                };

                return res;
            }
        }

        /// <summary>
        /// 上架入库复核
        /// </summary>
        /// <param name="receivingId">收货单Id</param>
        /// <returns></returns>
        [Transactional]
        public async Task SubmitLocalMaterialAsync(string receivingId)
        {
            string sqlMain = string.Empty;
            //查询收货单是否入库
            var indata = await Db.GetIQueryable<TD_InStorage>().Where(x => x.RecId == receivingId).FirstOrDefaultAsync();
            if (indata == null)
            {
                //获取收货单实际上架信息
                Expression<Func<PB_UpLoadList, PB_Location, PB_Material, PB_PackList, UpLoadListDTO>> select = (a, b, c, d) => new UpLoadListDTO
                {
                    ParentId = a.ParentId,
                    StorId = a.StorId,
                    LocalId = a.LocalId,
                    AreaId = b.AreaId,
                    RackId = b.RackId,
                    Price = c.Price,
                    Nums = a.Nums,
                    PackId = a.PackId,
                    MaterialId = a.MaterialId,
                    OldOrNew = a.PackId != "" ? d.OldOrNew : 1,
                    JobId = a.JobId
                };
                select = select.BuildExtendSelectExpre();
                var q = from a in Db.GetIQueryable<PB_UpLoadList>().AsExpandable()
                        join b in Db.GetIQueryable<PB_Location>() on a.LocalId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        join c in Db.GetIQueryable<PB_Material>() on a.MaterialId equals c.Id into ac
                        from c in ac.DefaultIfEmpty()
                        join d in Db.GetIQueryable<PB_PackList>() on a.PackId equals d.Id into ad
                        from d in ad.DefaultIfEmpty()
                        select @select.Invoke(a, b, c, d);
                var recedata = await q.Where(x => x.ParentId == receivingId).ToListAsync();
                var receivingdata = await Db.GetIQueryable<TD_Receiving>().Where(x => x.Id == receivingId).FirstOrDefaultAsync();
                //生成入库单id
                string sId = IdHelper.GetId();

                //数量汇总
                Double? dounum = 0;

                //添加入库单明细
                List<TD_InStorDetail> listdata = new List<TD_InStorDetail>();

                foreach (var item in recedata)
                {
                    TD_InStorDetail dedata = new TD_InStorDetail();
                    dedata.Id = IdHelper.GetId();
                    dedata.InStorId = sId;
                    dedata.StorId = item.StorId;
                    dedata.LocalId = item.LocalId;
                    dedata.AreaId = item.AreaId;
                    dedata.RackId = item.RackId;
                    dedata.MaterialId = item.MaterialId;
                    dedata.Price = Convert.ToDouble(item.Price);
                    dedata.TotalAmt = Convert.ToDouble(item.Price) * Convert.ToDouble(item.Nums);
                    dedata.Num = Convert.ToDouble(item.Nums);
                    dounum += Convert.ToDouble(item.Nums);
                    dedata.CreatorId = _operator.UserId;
                    dedata.CreateTime = DateTime.Now;
                    dedata.Deleted = false;
                    dedata.PackId = item.PackId;
                    dedata.OldOrNew = item.OldOrNew;
                    dedata.JobId = item.JobId;
                    dedata.TaskId = receivingdata.OrderId;
                    listdata.Add(dedata);
                }

                //入库明细
                List<TD_InStorRecord> listrecord = new List<TD_InStorRecord>();
                var listd = listdata.GroupBy(x => new { x.InStorId, x.StorId, x.MaterialId, x.Price }).Select(x => new { InStorId = x.Key.InStorId, StorId = x.Key.StorId, MaterialId = x.Key.MaterialId, Price = x.Key.Price, Nums = x.Sum(i => i.Num) }).ToList();
                foreach (var item in listd)
                {
                    TD_InStorRecord recodata = new TD_InStorRecord();
                    recodata.Id = IdHelper.GetId();
                    recodata.InStorId = item.InStorId;
                    recodata.StorId = item.StorId;
                    recodata.MaterialId = item.MaterialId;
                    recodata.Price = item.Price;
                    recodata.TotalAmt = item.Price * item.Nums;
                    recodata.Num = item.Nums;
                    recodata.CreateTime = DateTime.Now;
                    recodata.CreatorId = _operator.UserId;
                    recodata.Deleted = false;
                    listrecord.Add(recodata);
                }
                if (receivingdata.Type == "HalfProduct")
                {
                    receivingdata.Type = "Outsourcing";
                }
                //回货入库
                if (receivingdata.Type== "ReturnReceipt") {
                    receivingdata.Type = "Recycling";
                }
                //半成品入库、五金收货、原材新品收货
                if (receivingdata.Type == "HalfReceiving" || receivingdata.Type == "Hardware" || receivingdata.Type == "RawMaterial")
                {
                    receivingdata.Type = "Purchase";
                }
                //退货收货
                if (receivingdata.Type == "ReceReturn")
                {
                    receivingdata.Type = "Return";
                    Expression<Func<TD_RecDetail, PB_Material, TD_RecDetailPrintDTO>> selectd = (a, b) => new TD_RecDetailPrintDTO
                    {
                        Id = a.Id,
                        MaterialId = a.MaterialId,
                        RecId = a.RecId,
                        IsSingle = b.IsSingle,
                        MaterialName = b.Name
                    };
                    selectd = selectd.BuildExtendSelectExpre();
                    var qdata = from a in Db.GetIQueryable<TD_RecDetail>().AsExpandable()
                                join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                                from b in ab.DefaultIfEmpty()
                                select @selectd.Invoke(a, b);
                    var Materiallist = await qdata.Where(x => x.RecId == receivingId).ToListAsync();
                    string Memo = string.Empty;
                    foreach (var item in Materiallist)
                    {
                        Memo += item.MaterialName + ",";
                    }
                    Memo = Memo.Substring(0, Memo.Length - 1);
                    sqlMain += @" update PB_WarehousingNotice set Memo='" + Memo + "' where Id='" + receivingdata.RefCode + "'; ";
                }
                //成品入库
                if (receivingdata.Type == "Product")
                {
                    List<PB_JobBookingQrCode> JobBookingQrCode = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.RecId == receivingId).ToListAsync();
                    var jobdata = JobBookingQrCode.GroupBy(x => new { x.ParentId }).Select(x => new { ParentId = x.Key.ParentId }).FirstOrDefault();
                    if (jobdata != null)
                    {
                        if (jobdata.ParentId.IsNullOrEmpty())
                        {
                            receivingdata.Type = "Purchase";
                        }
                    }
                }

                var deptdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

                //生成入库单
                TD_InStorage InStoragedata = new TD_InStorage();
                InStoragedata.Id = sId;
                InStoragedata.RecId = receivingId;
                InStoragedata.StorId = receivingdata.StorId;
                InStoragedata.Code = GetTimeStamp();
                InStoragedata.InStorTime = DateTime.Now;
                InStoragedata.InType = receivingdata.Type;  //生产入库
                InStoragedata.RefCode = "";   //关联单号
                InStoragedata.Status = 0;  //待审核
                InStoragedata.TotalNum = Convert.ToDouble(dounum);
                InStoragedata.TotalAmt = 0;
                InStoragedata.CreateTime = DateTime.Now;
                InStoragedata.CreatorId = _operator.UserId;
                InStoragedata.Deleted = false;
                InStoragedata.DepId = deptdata.FactoryId;
                InStoragedata.QrCode = h_Warehousing + "," + sId;

                //添加入库单明细
                await Db.InsertAsync<TD_InStorDetail>(listdata);
                //添加入库明细
                await Db.InsertAsync<TD_InStorRecord>(listrecord);
                //添加入库单
                await Db.InsertAsync<TD_InStorage>(InStoragedata);
                //修改收货单的状态为已完成
                sqlMain += @" update TD_Receiving set Status=4,InNum='" + dounum + "',ToReviewId='" + _operator.UserId + "',ToReviewTime=NOW()  where Id='" + receivingId + "';";
                await ExecuteSqlAsync(sqlMain);

            }
            else
            {
                throw new BusException("收货单已入库不能重复入库");
            }
        }

        /// <summary>
        /// 上架入库提交
        /// </summary>
        /// <param name="receivingId">收货单Id</param>
        /// <returns></returns>
        [Transactional]
        public async Task SubmitReceingAsync(string receivingId)
        {
            string sqlMain = string.Empty;
            List<PB_UpLoadList> uplist = await Db.GetIQueryable<PB_UpLoadList>().Where(x => x.ParentId == receivingId).ToListAsync();
            if (uplist.Count == 0)
            {
                throw new BusException("请上架后提交");
            }

            List<TD_RecDetail> RecDetail = await Db.GetIQueryable<TD_RecDetail>().Where(x => x.RecId == receivingId).ToListAsync();
            int ToReviewStatus = 0;
            foreach (var item in RecDetail)
            {
                if (item.InNum != item.RecNum)
                {
                    ToReviewStatus = 1;
                }
            }

            Base_LinkType link = await Db.GetIQueryable<Base_LinkType>().Where(x => x.LinkType == "InStorage").FirstOrDefaultAsync();
            if (link.Whether == false)
            {
                //获取收货单实际上架信息
                Expression<Func<PB_UpLoadList, PB_Location, PB_Material, PB_PackList, UpLoadListDTO>> select = (a, b, c, d) => new UpLoadListDTO
                {
                    ParentId = a.ParentId,
                    StorId = a.StorId,
                    LocalId = a.LocalId,
                    AreaId = b.AreaId,
                    RackId = b.RackId,
                    Price = c.Price,
                    Nums = a.Nums,
                    PackId = a.PackId,
                    MaterialId = a.MaterialId,
                    OldOrNew = a.PackId != "" ? d.OldOrNew : 1,
                    JobId = a.JobId
                };
                select = select.BuildExtendSelectExpre();
                var q = from a in Db.GetIQueryable<PB_UpLoadList>().AsExpandable()
                        join b in Db.GetIQueryable<PB_Location>() on a.LocalId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        join c in Db.GetIQueryable<PB_Material>() on a.MaterialId equals c.Id into ac
                        from c in ac.DefaultIfEmpty()
                        join d in Db.GetIQueryable<PB_PackList>() on a.PackId equals d.Id into ad
                        from d in ad.DefaultIfEmpty()
                        select @select.Invoke(a, b, c, d);
                var recedata = await q.Where(x => x.ParentId == receivingId).ToListAsync();

                var receivingdata = await Db.GetIQueryable<TD_Receiving>().Where(x => x.Id == receivingId).FirstOrDefaultAsync();

                //生成入库单id
                string sId = IdHelper.GetId();

                //数量汇总
                Double? dounum = 0;

                //添加入库单明细
                List<TD_InStorDetail> listdata = new List<TD_InStorDetail>();
                List<IT_RecordBook> iT_RecordBooks = new List<IT_RecordBook>();
                foreach (var item in recedata)
                {
                    TD_InStorDetail dedata = new TD_InStorDetail();
                    dedata.Id = IdHelper.GetId();
                    dedata.InStorId = sId;
                    dedata.StorId = item.StorId;
                    dedata.LocalId = item.LocalId;
                    dedata.AreaId = item.AreaId;
                    dedata.RackId = item.RackId;
                    dedata.MaterialId = item.MaterialId;
                    dedata.Price = Convert.ToDouble(item.Price);
                    dedata.TotalAmt = Convert.ToDouble(item.Price) * Convert.ToDouble(item.Nums);
                    dedata.Num = Convert.ToDouble(item.Nums);
                    dounum += Convert.ToDouble(item.Nums);
                    dedata.CreatorId = _operator.UserId;
                    dedata.CreateTime = DateTime.Now;
                    dedata.Deleted = false;
                    dedata.PackId = item.PackId;
                    dedata.OldOrNew = item.OldOrNew;
                    dedata.JobId = item.JobId;
                    dedata.TaskId = receivingdata.OrderId;
                    listdata.Add(dedata);
                    IT_RecordBook iT_RecordBook = new IT_RecordBook();
                    iT_RecordBook.Id = IdHelper.GetId();
                    iT_RecordBook.Type = "In";
                    iT_RecordBook.RefCode = sId;
                    iT_RecordBook.FromStorId = "";
                    iT_RecordBook.FromLocalId = "";
                    iT_RecordBook.ToStorId = item.StorId;
                    iT_RecordBook.ToLocalId = item.LocalId;
                    iT_RecordBook.MaterialId = item.MaterialId;
                    iT_RecordBook.MeasureId = "";
                    iT_RecordBook.BarCode = "";
                    iT_RecordBook.BatchNo = "";
                    iT_RecordBook.Num = Convert.ToDouble(item.Nums);
                    iT_RecordBook.CreateTime = DateTime.Now;
                    iT_RecordBook.CreatorId = _operator.UserId;
                    iT_RecordBook.Deleted = false;
                    iT_RecordBooks.Add(iT_RecordBook);
                }

                //入库明细
                List<TD_InStorRecord> listrecord = new List<TD_InStorRecord>();
                var listd = listdata.GroupBy(x => new { x.InStorId, x.StorId, x.MaterialId, x.Price }).Select(x => new { InStorId = x.Key.InStorId, StorId = x.Key.StorId, MaterialId = x.Key.MaterialId, Price = x.Key.Price, Nums = x.Sum(i => i.Num) }).ToList();
                foreach (var item in listd)
                {
                    TD_InStorRecord recodata = new TD_InStorRecord();
                    recodata.Id = IdHelper.GetId();
                    recodata.InStorId = item.InStorId;
                    recodata.StorId = item.StorId;
                    recodata.MaterialId = item.MaterialId;
                    recodata.Price = item.Price;
                    recodata.TotalAmt = item.Price * item.Nums;
                    recodata.Num = item.Nums;
                    recodata.CreateTime = DateTime.Now;
                    recodata.CreatorId = _operator.UserId;
                    recodata.Deleted = false;
                    listrecord.Add(recodata);
                }

                //外协半成品收货
                if (receivingdata.Type == "HalfProduct")
                {
                    receivingdata.Type = "Outsourcing";
                }
                //回货入库
                if (receivingdata.Type == "ReturnReceipt")
                {
                    receivingdata.Type = "Recycling";
                }
                //半成品入库、五金收货、原材新品收货
                if (receivingdata.Type == "HalfReceiving" || receivingdata.Type == "Hardware" || receivingdata.Type == "RawMaterial")
                {
                    receivingdata.Type = "Purchase";
                }
                //退货收货
                if (receivingdata.Type == "ReceReturn")
                {
                    receivingdata.Type = "Return";
                    Expression<Func<TD_RecDetail, PB_Material, TD_RecDetailPrintDTO>> selectd = (a, b) => new TD_RecDetailPrintDTO
                    {
                        Id = a.Id,
                        MaterialId = a.MaterialId,
                        RecId = a.RecId,
                        IsSingle = b.IsSingle,
                        MaterialName = b.Name
                    };
                    selectd = selectd.BuildExtendSelectExpre();
                    var qdata = from a in Db.GetIQueryable<TD_RecDetail>().AsExpandable()
                                join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                                from b in ab.DefaultIfEmpty()
                                select @selectd.Invoke(a, b);
                    var Materiallist = await qdata.Where(x => x.RecId == receivingId).ToListAsync();
                    string Memo = string.Empty;
                    foreach (var item in Materiallist)
                    {
                        Memo += item.MaterialName + ",";
                    }
                    Memo = Memo.Substring(0, Memo.Length - 1);
                    sqlMain += @" update PB_WarehousingNotice set Memo='" + Memo + "' where Id='" + receivingdata.RefCode + "'; ";
                }
                //成品收货
                if (receivingdata.Type == "Product")
                {
                    List<PB_JobBookingQrCode> JobBookingQrCode = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.RecId == receivingId).ToListAsync();
                    var jobdata = JobBookingQrCode.GroupBy(x => new { x.ParentId }).Select(x => new { ParentId = x.Key.ParentId }).FirstOrDefault();
                    if (jobdata != null)
                    {
                        if (jobdata.ParentId.IsNullOrEmpty())
                        {
                            receivingdata.Type = "Purchase";
                        }
                    }
                }

                var deptdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

                //生成入库单
                TD_InStorage InStoragedata = new TD_InStorage();
                InStoragedata.Id = sId;
                InStoragedata.RecId = receivingId;
                InStoragedata.StorId = receivingdata.StorId;
                InStoragedata.Code = GetTimeStamp();
                InStoragedata.InStorTime = DateTime.Now;
                InStoragedata.InType = receivingdata.Type;  //生产入库
                InStoragedata.RefCode = "";   //关联单号
                InStoragedata.Status = 0;  //待审核
                InStoragedata.TotalNum = Convert.ToDouble(dounum);
                InStoragedata.TotalAmt = 0;
                InStoragedata.CreateTime = DateTime.Now;
                InStoragedata.CreatorId = _operator.UserId;
                InStoragedata.Deleted = false;
                InStoragedata.DepId = deptdata.FactoryId;
                InStoragedata.QrCode = h_Warehousing + "," + sId;

                //添加入库单明细
                await Db.InsertAsync<TD_InStorDetail>(listdata);
                //添加台账数据
                await Db.InsertAsync<IT_RecordBook>(iT_RecordBooks);

                //添加入库明细
                await Db.InsertAsync<TD_InStorRecord>(listrecord);
                //添加入库单
                await Db.InsertAsync<TD_InStorage>(InStoragedata);
                //修改收货单的状态为已完成
                sqlMain += @" update TD_Receiving set Status=4,ToReviewStatus='" + ToReviewStatus + "',InNum='" + dounum + "',ToReviewId='" + _operator.UserId + "',ToReviewTime=NOW()  where Id='" + receivingId + "'; ";
                await ExecuteSqlAsync(sqlMain);
            }
            else if(link.Whether == true)
            {
                //修改收货单的状态为已完成
                await ExecuteSqlAsync("update TD_Receiving set Status=6,ToReviewStatus='" + ToReviewStatus + "' where Id='" + receivingId + "'");
            }
        }

        /// <summary>
        /// 收货单复核退回改为开始作业状态
        /// </summary>
        /// <param name="receivingId">收货单Id</param>
        /// <returns></returns>
        public async Task UpReceReturnAsync(string receivingId)
        {
            //修改收货单的状态为已完成
            await ExecuteSqlAsync("update TD_Receiving set Status=3,ToReviewStatus=NULL where Id='" + receivingId + "'");
        }

        /// <summary>
        /// 收货单打码明细
        /// </summary>
        /// <param name="recid">收货单id</param>
        /// <returns></returns>
        public async Task<List<TD_RecDetailPrintDTO>> GetRecDetailPrintListAsync(string recid)
        {
            string sqlMain = @"select distinct a.*,b.`Code` as MaterialCode,b.`Name` as MaterialName,b.Spec as MaterialSpec,b.IsSingle,IFNULL(c.Nums,0) AS Nums,IFNULL(d.packnums,0) AS packnums from TD_RecDetail as a join PB_Material as b on a.MaterialId=b.Id left join (select MaterialId,IFNULL(COUNT(MaterialId),0) as nums from PB_JobBookingQrCode where RecId='" + recid + "' group by MaterialId) as c on a.MaterialId=c.MaterialId left join (select MaterialId,Count(PackId) as packnums from PB_JobBookingQrCode where RecId='" + recid + "' group by MaterialId) as d on a.MaterialId=d.MaterialId where a.RecId='" + recid + "'";
            var listdata = await Db.GetListBySqlAsync<TD_RecDetailPrintDTO>(sqlMain);
            return listdata;

        }

        /// <summary>
        /// 收货单物料二维码打印
        /// </summary>
        /// <param name="data"></param>
        /// <param name="_mongodbOptions"></param>
        /// <param name="_redisOptions"></param>
        /// 推送队列增加批次    2022-03-01  赵锦涛
        /// <returns></returns>
        [Transactional]
        public async Task RecDetailPrintListDataAsync(RecDetailPrintDTO data, MongoDBOptions _mongodbOptions, RedisOptions _redisOptions)
        {
            //先查询要打印的物料信息
            Expression<Func<TD_RecDetail, PB_Material, Base_Department, PB_MaterialType, PB_Supplier, RecDetailPrintDataDTO>> select = (a, b, c, d, e) => new RecDetailPrintDataDTO
            {
                Id = a.Id,
                RecId = a.RecId,
                MaterialId = a.MaterialId,
                RecNum = a.RecNum,
                MaterialCode = b.Code,
                MaterialName = b.Name,
                MaterialSpec = b.Spec,
                IsNumber = b.IsNumber,
                DeptId = b.DeptId,
                DeptName = c.Name,
                MaterialType = d.Name,
                PackageNum = b.PackageNum,
                MaxPackageNum = b.MaxPackageNum,
                IsProduct = b.IsProduct,
                ProductCode = b.ProductCode,
                IsSingle = b.IsSingle,
                IsMine = b.IsMine,
                SupplierName = e.Name,
                IsSpec = b.IsSpec,
                IsStandard=b.IsStandard,
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<TD_RecDetail>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<Base_Department>() on b.DeptId equals c.Id into bc
                    from c in bc.DefaultIfEmpty()
                    join d in Db.GetIQueryable<PB_MaterialType>() on b.MaterialTypeId equals d.Id into bd
                    from d in bd.DefaultIfEmpty()
                    join e in Db.GetIQueryable<PB_Supplier>() on a.Id equals e.Id into ae
                    from e in ae.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d, e);
            var listD = await q.Where(x => data.liststr.Contains(x.Id)).ToListAsync();
            if (listD.Count == 0)
            {
                throw new BusException("请检查数据的正确性");
            }

            //时间戳
            string timestamp = GetTimeStamp();
            //推送队列批次
            string strguid = Guid.NewGuid().ToString("N");

            //实例化Redis操作类
            _redisOptions.DbChannel = (int)Redis_Type.redis6;
            RedisSetHelper redis = new RedisSetHelper(_redisOptions);
            List<PB_PackList> listpack = new List<PB_PackList>();
            List<PB_PackListInfo> listinfo = new List<PB_PackListInfo>();
            List<PB_PackMaterialCount> PackMaterialCountList = new List<PB_PackMaterialCount>();
            List<PrintQueue> listdata = new List<PrintQueue>();
            List<PB_JobBookingQrCode> listcode = new List<PB_JobBookingQrCode>();
            List<PB_JobBookingDetailed> pbdetailed = new List<PB_JobBookingDetailed>();
            Base_User bdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

            //获取收货单信息
            TD_Receiving Receiving = await Db.GetIQueryable<TD_Receiving>().Where(x => x.Id == data.recid).FirstOrDefaultAsync();

            OutBillOrderDTO OutBillOrder = new OutBillOrderDTO();

            //收货单是外协成品收货时,获取收货单对应外协订单
            if (Receiving.Type == "HalfProduct")
            {
                //先查询要打印的物料信息
                Expression<Func<PB_OutsourcingBillReturnDetail, PB_OutsourcingBill, PB_ProductionOrder, PB_DesignList, OutBillOrderDTO>> halfselect = (a, b, c, d) => new OutBillOrderDTO
                {
                    RecId = a.RecId,
                    ProjectId = d.ProjectId,
                    BuildingNumberID = d.BuildingNumberID
                };
                halfselect = halfselect.BuildExtendSelectExpre();
                var halfq = from a in Db.GetIQueryable<PB_OutsourcingBillReturnDetail>().AsExpandable()
                            join b in Db.GetIQueryable<PB_OutsourcingBill>() on a.ParentId equals b.Id into ab
                            from b in ab.DefaultIfEmpty()
                            join c in Db.GetIQueryable<PB_ProductionOrder>() on b.RefCode equals c.Id into bc
                            from c in bc.DefaultIfEmpty()
                            join d in Db.GetIQueryable<PB_DesignList>() on c.DesignId equals d.Id into cd
                            from d in cd.DefaultIfEmpty()
                            select @halfselect.Invoke(a, b, c, d);
                OutBillOrder = await halfq.Where(x => x.RecId == data.recid).FirstOrDefaultAsync();
                if (!OutBillOrder.IsNullOrEmpty())
                {
                    if (!OutBillOrder.ProjectId.IsNullOrEmpty())
                    {
                        PB_Project Project = await Db.GetIQueryable<PB_Project>().Where(x => x.Id == OutBillOrder.ProjectId).FirstOrDefaultAsync();

                        PB_Buildingnumber Buildingnumber = await Db.GetIQueryable<PB_Buildingnumber>().Where(x => x.Id == OutBillOrder.BuildingNumberID).FirstOrDefaultAsync();

                        OutBillOrder.ProjectName = Project == null ? "" : Project.Name;
                        OutBillOrder.BuildingNumberName = Buildingnumber == null ? "" : Buildingnumber.Buildingnumber;
                    }
                }
            }

            var deptdata = await _opdept.GetOperatorDept();
            //判断是否是是自动打包，否
            if (data.IsPushQueue == false)
            {
                foreach (var item in listD)
                {
                    if (item.IsSingle == true)
                    {
                        PrintQueue pq = new PrintQueue();
                        PB_JobBookingQrCode jkcode = new PB_JobBookingQrCode();

                        string jobcodeId = IdHelper.GetId();   //成品档案表ID
                        pq.Id = IdHelper.GetId();
                        pq.Name = item.MaterialName;
                        pq.Date = DateTime.Now.ToString("yyyy-MM-dd");
                        pq.Dept = item.IsMine == true ? deptdata.DeptName : item.SupplierName;
                        if (RedisSetHelper.Exists("QualityTestingNumber"))
                        {
                            string thedate = DateTime.Now.ToString("yyyy-MM-dd");
                            if (redis.GetString("QualityTestingTime") == thedate)
                            {
                                redis.SetString("QualityTestingNumber", (Convert.ToInt32(redis.GetString("QualityTestingNumber")) + 1).ToString());
                                pq.No = jobcodeId + "," + redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                            }
                            else
                            {
                                redis.SetString("QualityTestingTime", thedate);
                                redis.SetString("QualityTestingNumber", "1");
                                pq.No = jobcodeId + "," + redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                            }
                        }
                        else
                        {
                            redis.SetString("QualityTestingNumber", "0");
                        }
                        pq.QrCode = h_Material + "," + item.MaterialId;
                        pq.TypeName = item.MaterialSpec;
                        pq.Type = Skill_Type.Statistics.ToString();
                        pq.Status = item.RecNum.ToString();
                        pq.Printer = data.MaterialPrinterId;
                        pq.IsProduct = item.IsProduct;
                        pq.BatchNumber = strguid;
                        pq.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                        pq.JobCount = 1;
                        if (Receiving.Type == "HalfProduct")
                        {
                            pq.ProjectName = OutBillOrder == null ? "" : OutBillOrder.ProjectName;
                            pq.BuildingNumberName = OutBillOrder == null ? "" : OutBillOrder.BuildingNumberName;
                        }
                        else
                        {
                            pq.ProjectName = "";
                            pq.BuildingNumberName = "";
                        }
                        pq.IsStandard = item.IsStandard == false ? 0 : 1;
                        listdata.Add(pq);
                        jkcode.Id = jobcodeId;
                        jkcode.QrCode = h_Material + "," + item.MaterialId;
                        jkcode.MaterialId = item.MaterialId;
                        jkcode.MaterialName = item.MaterialName;
                        jkcode.OldOrNew = 1;
                        jkcode.RecId = data.recid;
                        jkcode.PackStatus = 0;
                        listcode.Add(jkcode);
                        PB_JobBookingDetailed pbdata = new PB_JobBookingDetailed();
                        pbdata.Id = IdHelper.GetId();
                        pbdata.No = item.Id;
                        pbdata.Nums = 1;
                        pbdata.DeptId = deptdata.DetpId;
                        pbdata.OperationUserId = _operator.UserId;
                        pbdata.OperationUserName = bdata.RealName;
                        pbdata.OperationTime = DateTime.Now;
                        pbdata.Type = 4;
                        pbdata.OldOrNew = 1;
                        pbdata.PrinterId = data.MaterialPrinterId;
                        pbdetailed.Add(pbdata);
                    }
                    else
                    {
                        if (item.IsNumber == true)
                        {
                            for (int i = 0; i < item.RecNum; i++)
                            {
                                PrintQueue pq = new PrintQueue();
                                PB_JobBookingQrCode jkcode = new PB_JobBookingQrCode();

                                string jobcodeId = IdHelper.GetId();   //成品档案表ID
                                pq.Id = IdHelper.GetId();
                                pq.Name = item.MaterialName;
                                pq.Date = DateTime.Now.ToString("yyyy-MM-dd");
                                pq.Dept = item.IsMine == true ? deptdata.DeptName : item.SupplierName;
                                if (RedisSetHelper.Exists("QualityTestingNumber"))
                                {
                                    string thedate = DateTime.Now.ToString("yyyy-MM-dd");
                                    if (redis.GetString("QualityTestingTime") == thedate)
                                    {
                                        redis.SetString("QualityTestingNumber", (Convert.ToInt32(redis.GetString("QualityTestingNumber")) + 1).ToString());
                                        pq.No = jobcodeId + "," + redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                        jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                    }
                                    else
                                    {
                                        redis.SetString("QualityTestingTime", thedate);
                                        redis.SetString("QualityTestingNumber", "1");
                                        pq.No = jobcodeId + "," + redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                        jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                    }
                                }
                                else
                                {
                                    redis.SetString("QualityTestingNumber", "0");
                                }
                                pq.QrCode = h_FinishedProduct + "," + jobcodeId;
                                pq.TypeName = item.MaterialSpec;
                                pq.Type = Skill_Type.Statistics.ToString();
                                pq.Status = "0";
                                pq.Printer = data.MaterialPrinterId;
                                pq.IsProduct = item.IsProduct;
                                pq.BatchNumber = strguid;
                                pq.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                                if (Receiving.Type == "HalfProduct")
                                {
                                    pq.ProjectName = OutBillOrder == null ? "" : OutBillOrder.ProjectName;
                                    pq.BuildingNumberName = OutBillOrder == null ? "" : OutBillOrder.BuildingNumberName;
                                }
                                else
                                {
                                    pq.ProjectName = "";
                                    pq.BuildingNumberName = "";
                                }
                                pq.IsStandard = item.IsStandard == false ? 0 : 1;
                                pq.JobCount = item.RecNum;
                                listdata.Add(pq);
                                jkcode.Id = jobcodeId;
                                jkcode.QrCode = h_FinishedProduct + "," + jobcodeId;
                                jkcode.MaterialId = item.MaterialId;
                                jkcode.MaterialName = item.MaterialName;
                                jkcode.OldOrNew = 1;
                                jkcode.RecId = data.recid;
                                jkcode.PackStatus = 0;
                                listcode.Add(jkcode);
                            }
                            PB_JobBookingDetailed pbdata = new PB_JobBookingDetailed();
                            pbdata.Id = IdHelper.GetId();
                            pbdata.No = item.Id;
                            pbdata.Nums = item.RecNum;
                            pbdata.DeptId = deptdata.DetpId;
                            pbdata.OperationUserId = _operator.UserId;
                            pbdata.OperationUserName = bdata.RealName;
                            pbdata.OperationTime = DateTime.Now;
                            pbdata.Type = 4;
                            pbdata.OldOrNew = 1;
                            pbdata.PrinterId = data.MaterialPrinterId;
                            pbdetailed.Add(pbdata);
                        }
                        else
                        {
                            PrintQueue pq = new PrintQueue();
                            PB_JobBookingQrCode jkcode = new PB_JobBookingQrCode();

                            string jobcodeId = IdHelper.GetId();   //成品档案表ID
                            pq.Id = IdHelper.GetId();
                            pq.Name = item.MaterialName;
                            pq.Date = DateTime.Now.ToString("yyyy-MM-dd");
                            pq.Dept = item.IsMine == true ? deptdata.DeptName : item.SupplierName;
                            if (RedisSetHelper.Exists("QualityTestingNumber"))
                            {
                                string thedate = DateTime.Now.ToString("yyyy-MM-dd");
                                if (redis.GetString("QualityTestingTime") == thedate)
                                {
                                    redis.SetString("QualityTestingNumber", (Convert.ToInt32(redis.GetString("QualityTestingNumber")) + 1).ToString());
                                    pq.No = jobcodeId + "," + redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                    jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                }
                                else
                                {
                                    redis.SetString("QualityTestingTime", thedate);
                                    redis.SetString("QualityTestingNumber", "1");
                                    pq.No = jobcodeId + "," + redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                    jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                }
                            }
                            else
                            {
                                redis.SetString("QualityTestingNumber", "0");
                            }
                            pq.QrCode = h_FinishedProduct + "," + jobcodeId;
                            pq.TypeName = item.MaterialSpec;
                            pq.Type = Skill_Type.Statistics.ToString();
                            pq.Status = "0";
                            pq.Printer = data.MaterialPrinterId;
                            pq.IsProduct = item.IsProduct;
                            pq.BatchNumber = strguid;
                            pq.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                            pq.JobCount = 1;
                            if (Receiving.Type == "HalfProduct")
                            {
                                pq.ProjectName = OutBillOrder == null ? "" : OutBillOrder.ProjectName;
                                pq.BuildingNumberName = OutBillOrder == null ? "" : OutBillOrder.BuildingNumberName;
                            }
                            else
                            {
                                pq.ProjectName = "";
                                pq.BuildingNumberName = "";
                            }
                            pq.IsStandard = item.IsStandard == false ? 0 : 1;
                            listdata.Add(pq);
                            jkcode.Id = jobcodeId;
                            jkcode.QrCode = h_FinishedProduct + "," + jobcodeId;
                            jkcode.MaterialId = item.MaterialId;
                            jkcode.MaterialName = item.MaterialName;
                            jkcode.OldOrNew = 1;
                            jkcode.RecId = data.recid;
                            jkcode.PackStatus = 0;
                            listcode.Add(jkcode);
                            PB_JobBookingDetailed pbdata = new PB_JobBookingDetailed();
                            pbdata.Id = IdHelper.GetId();
                            pbdata.No = item.Id;
                            pbdata.Nums = 1;
                            pbdata.DeptId = deptdata.DetpId;
                            pbdata.OperationUserId = _operator.UserId;
                            pbdata.OperationUserName = bdata.RealName;
                            pbdata.OperationTime = DateTime.Now;
                            pbdata.Type = 4;
                            pbdata.OldOrNew = 1;
                            pbdata.PrinterId = data.MaterialPrinterId;
                            pbdetailed.Add(pbdata);
                        }
                    }
                }
            }
            else //判断是否是是自动打包，是
            {
                //推送队列包批次
                string packguid = "";
                foreach (var item in listD)
                {
                    packguid = Guid.NewGuid().ToString("N");
                    //定义是否是大小包
                    bool bltrueorfalse = false;
                    //计算自动打包的数量
                    decimal d = 0;
                    if (data.IsMax == true)
                    {
                        if (item.IsSpec == true)
                        {
                            if (item.MaxPackageNum == 0 || item.MaxPackageNum.IsNullOrEmpty())
                            {
                                throw new BusException("请维护" + item.MaterialName + "的大包装数量!");
                            }
                            d = Math.Ceiling(Convert.ToDecimal(item.RecNum) / Convert.ToDecimal(item.MaxPackageNum));
                            bltrueorfalse = true;
                        }
                        else
                        {
                            if (item.PackageNum == 0 || item.PackageNum.IsNullOrEmpty())
                            {
                                throw new BusException("请维护" + item.MaterialName + "的小包装数量!");
                            }
                            d = Math.Ceiling(Convert.ToDecimal(item.RecNum) / Convert.ToDecimal(item.PackageNum));
                        }
                    }
                    else
                    {
                        if (item.PackageNum == 0 || item.PackageNum.IsNullOrEmpty())
                        {
                            throw new BusException("请维护" + item.MaterialName + "的小包装数量!");
                        }
                        d = Math.Ceiling(Convert.ToDecimal(item.RecNum) / Convert.ToDecimal(item.PackageNum));
                    }
                    //是否是序列化管理
                    if (item.IsNumber == true)
                    {
                        //TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                        //string sjtime = Convert.ToInt64(ts.TotalSeconds).ToString();
                        double dcount = 0;
                        double dindex = 0;
                        //循环要生成的包数量
                        for (int i = 0; i < d; i++)
                        {
                            PrintQueue printdata = new PrintQueue();
                            PB_PackList packdata = new PB_PackList();
                            string dataName = "bag_" + timestamp + "_" + (i + 1);
                            string dataId = IdHelper.GetId();
                            dcount = bltrueorfalse == true ? Convert.ToDouble(item.MaxPackageNum) * (i + 1) : Convert.ToDouble(item.PackageNum) * (i + 1);
                            if (dcount <= item.RecNum)
                            {
                                dindex = bltrueorfalse == true ? Convert.ToDouble(item.MaxPackageNum) : Convert.ToDouble(item.PackageNum);
                            }
                            else
                            {
                                dindex = bltrueorfalse == true ? (item.RecNum - Convert.ToDouble(item.MaxPackageNum) * i) : (item.RecNum - Convert.ToDouble(item.PackageNum) * i);
                            }
                            for (int j = 0; j < dindex; j++)
                            {
                                if (j == 0)
                                {
                                    packdata.BoxName = item.MaterialName;
                                    packdata.MaterialId = item.MaterialId;
                                    printdata.Name = item.MaterialName;
                                    printdata.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                                    printdata.IsProduct = item.IsProduct;
                                }
                                PB_JobBookingQrCode jkcode = new PB_JobBookingQrCode();
                                string jobcodeId = IdHelper.GetId();   //成品档案表ID
                                if (RedisSetHelper.Exists("QualityTestingNumber"))
                                {
                                    string thedate = DateTime.Now.ToString("yyyy-MM-dd");
                                    if (redis.GetString("QualityTestingTime") == thedate)
                                    {
                                        redis.SetString("QualityTestingNumber", (Convert.ToInt32(redis.GetString("QualityTestingNumber")) + 1).ToString());
                                        jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                    }
                                    else
                                    {
                                        redis.SetString("QualityTestingTime", thedate);
                                        redis.SetString("QualityTestingNumber", "1");
                                        jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                    }
                                }
                                else
                                {
                                    redis.SetString("QualityTestingNumber", "0");
                                }
                                jkcode.Id = jobcodeId;
                                jkcode.QrCode = h_FinishedProduct + "," + jobcodeId;
                                jkcode.MaterialId = item.MaterialId;
                                jkcode.MaterialName = item.MaterialName;
                                jkcode.OldOrNew = 1;
                                jkcode.RecId = data.recid;
                                jkcode.PackId = dataId;
                                jkcode.PackStatus = 0;
                                listcode.Add(jkcode);

                                //包明细
                                PB_PackListInfo infodata = new PB_PackListInfo();
                                infodata.Id = IdHelper.GetId();
                                infodata.PackId = dataId;
                                infodata.JobBookingId = jobcodeId;
                                infodata.CreatorId = _operator.UserId;
                                infodata.CreatorName = bdata.RealName;
                                infodata.CreatorTime = DateTime.Now;
                                infodata.Deleted = false;
                                infodata.OldOrNew = 1;
                                listinfo.Add(infodata);
                                ////成品码推送
                                //PrintQueue materprint = new PrintQueue();
                                //materprint.Id = IdHelper.GetId();
                                //materprint.No = jobcodeId;
                                //materprint.Name = item.MaterialName;
                                //materprint.TypeName = item.MaterialType;
                                //materprint.Date = DateTime.Now.ToString("yyyy-MM-dd");
                                //materprint.Dept = deptdata.DeptName;
                                //materprint.QrCode = h_FinishedProduct + "," + jobcodeId;
                                //materprint.Type = Skill_Type.Statistics.ToString();
                                //materprint.Status = "0";
                                //materprint.Printer = data.MaterialPrinterId;
                                //materprint.IsProduct = item.IsProduct;
                                //materprint.Code= item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                                //listdata.Add(materprint);
                            }



                            //包信息
                            packdata.Id = dataId;
                            packdata.DeptId = bdata.DepartmentId;
                            packdata.BoxNo = dataName;
                            packdata.Status = 1;
                            packdata.Type = 1;
                            packdata.State = true;
                            packdata.CreateTime = DateTime.Now;
                            packdata.CreatorId = _operator.UserId;
                            packdata.Deleted = false;
                            packdata.CreatorName = bdata.RealName;
                            packdata.Nums = dindex;
                            packdata.QrCode = h_Pack + "," + dataId;
                            packdata.WorkshopId = bdata.DepartmentId;
                            packdata.OldOrNew = 1;
                            packdata.PackageType = 0;
                            packdata.IsUnpacking = dindex == item.PackageNum ? false : true;
                            listpack.Add(packdata);

                            PB_PackMaterialCount PackMaterialCount = new PB_PackMaterialCount();
                            PackMaterialCount.Id = IdHelper.GetId();
                            PackMaterialCount.PackId = dataId;
                            PackMaterialCount.MaterialId = item.MaterialId;
                            PackMaterialCount.Nums = dindex;
                            PackMaterialCountList.Add(PackMaterialCount);

                            //推送包信息到打印队列
                            printdata.Id = IdHelper.GetId();
                            printdata.No = dataId;
                            printdata.Date = DateTime.Now.ToString("yyyy-MM-dd");
                            printdata.Dept = item.IsMine == true ? deptdata.DeptName : item.SupplierName;
                            printdata.BatchNumber = packguid;
                            printdata.QrCode = h_Pack + "," + dataId;
                            printdata.Type = Skill_Type.Package.ToString();
                            printdata.Status = dindex.ToString();
                            printdata.Printer = data.PrinterId;
                            printdata.TypeName = item.MaterialSpec;
                            printdata.JobCount = Convert.ToDouble(d);
                            listdata.Add(printdata);
                        }

                        //生成成品记录
                        PB_JobBookingDetailed pbdata = new PB_JobBookingDetailed();
                        pbdata.Id = IdHelper.GetId();
                        pbdata.No = item.Id;
                        pbdata.Nums = item.RecNum;
                        pbdata.DeptId = deptdata.DetpId;
                        pbdata.OperationUserId = _operator.UserId;
                        pbdata.OperationUserName = bdata.RealName;
                        pbdata.OperationTime = DateTime.Now;
                        pbdata.Type = 4;
                        pbdata.OldOrNew = 1;
                        pbdata.PrinterId = data.PrinterId;
                        pbdetailed.Add(pbdata);
                    }
                    else
                    {
                        //TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                        //string sjtime = Convert.ToInt64(ts.TotalSeconds).ToString();
                        double dcount = 0;
                        double dindex = 0;
                        //循环要生成的包数量
                        for (int i = 0; i < d; i++)
                        {
                            dcount = Convert.ToDouble(item.PackageNum) * (i + 1);
                            if (dcount <= item.RecNum)
                            {
                                dindex = Convert.ToDouble(item.PackageNum);
                            }
                            else
                            {
                                dindex = item.RecNum - Convert.ToDouble(item.PackageNum) * i;
                            }
                            PB_JobBookingQrCode jkcode = new PB_JobBookingQrCode();
                            string dataId = IdHelper.GetId();
                            string jobcodeId = IdHelper.GetId();   //成品档案表ID
                            if (RedisSetHelper.Exists("QualityTestingNumber"))
                            {
                                string thedate = DateTime.Now.ToString("yyyy-MM-dd");
                                if (redis.GetString("QualityTestingTime") == thedate)
                                {
                                    redis.SetString("QualityTestingNumber", (Convert.ToInt32(redis.GetString("QualityTestingNumber")) + 1).ToString());
                                    jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                }
                                else
                                {
                                    redis.SetString("QualityTestingTime", thedate);
                                    redis.SetString("QualityTestingNumber", "1");
                                    jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                }
                            }
                            else
                            {
                                redis.SetString("QualityTestingNumber", "0");
                            }
                            jkcode.Id = jobcodeId;
                            jkcode.QrCode = h_FinishedProduct + "," + jobcodeId;
                            jkcode.MaterialId = item.MaterialId;
                            jkcode.MaterialName = item.MaterialName;
                            jkcode.OldOrNew = 1;
                            jkcode.RecId = data.recid;
                            jkcode.PackId = dataId;
                            jkcode.PackStatus = 0;
                            listcode.Add(jkcode);

                            ////成品码推送
                            //PrintQueue materprint = new PrintQueue();
                            //materprint.Id = IdHelper.GetId();
                            //materprint.No = jobcodeId;
                            //materprint.Name = item.MaterialName;
                            //materprint.TypeName = item.MaterialType;
                            //materprint.Date = DateTime.Now.ToString("yyyy-MM-dd");
                            //materprint.Dept = deptdata.DeptName;
                            //materprint.QrCode = h_FinishedProduct + "," + jobcodeId;
                            //materprint.Type = Skill_Type.Statistics.ToString();
                            //materprint.Status = "0";
                            //materprint.Printer = data.MaterialPrinterId;
                            //materprint.IsProduct = item.IsProduct;
                            //materprint.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                            //listdata.Add(materprint);

                            //生成包信息
                            PB_PackList packdata = new PB_PackList();
                            string dataName = "bag_" + timestamp + "_" + (i + 1);
                            
                            packdata.Id = dataId;
                            packdata.DeptId = bdata.DepartmentId;
                            packdata.BoxNo = dataName;
                            packdata.BoxName = item.MaterialName;
                            packdata.MaterialId = item.MaterialId;
                            packdata.Nums = dindex;
                            packdata.State = false;
                            packdata.QrCode = h_Pack + "," + dataId;
                            packdata.Type = 1;
                            packdata.CreatorId = _operator.UserId;
                            packdata.CreateTime = DateTime.Now;
                            packdata.CreatorName = bdata.RealName;
                            packdata.WorkshopId = bdata.DepartmentId;
                            packdata.Status = 1;
                            packdata.OldOrNew = 1;
                            packdata.PackageType = 0;
                            packdata.IsUnpacking = dindex == item.PackageNum ? false : true;
                            listpack.Add(packdata);

                            PB_PackMaterialCount PackMaterialCount = new PB_PackMaterialCount();
                            PackMaterialCount.Id = IdHelper.GetId();
                            PackMaterialCount.PackId = dataId;
                            PackMaterialCount.MaterialId = item.MaterialId;
                            PackMaterialCount.Nums = dindex;
                            PackMaterialCountList.Add(PackMaterialCount);

                            //生成包明细
                            PB_PackListInfo infodata = new PB_PackListInfo();
                            infodata.Id = IdHelper.GetId();
                            infodata.PackId = dataId;
                            infodata.JobBookingId = jobcodeId;
                            infodata.CreatorId = _operator.UserId;
                            infodata.CreatorName = bdata.RealName;
                            infodata.CreatorTime = DateTime.Now;
                            infodata.Deleted = false;
                            infodata.OldOrNew = 1;
                            listinfo.Add(infodata);

                            //包码推送
                            PrintQueue printdata = new PrintQueue();
                            printdata.Id = IdHelper.GetId();
                            printdata.No = dataId;
                            printdata.Name = item.MaterialName;
                            printdata.Date = DateTime.Now.ToString("yyyy-MM-dd");
                            printdata.Dept = item.IsMine == true ? deptdata.DeptName : item.SupplierName;
                            printdata.QrCode = h_Pack + "," + dataId;
                            printdata.Type = Skill_Type.Package.ToString();
                            printdata.Status = dindex.ToString();
                            printdata.Printer = data.PrinterId;
                            printdata.TypeName = item.MaterialSpec;
                            printdata.BatchNumber = packguid;
                            printdata.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                            printdata.IsProduct = item.IsProduct;
                            printdata.JobCount = Convert.ToDouble(d);
                            listdata.Add(printdata);
                        }
                        //添加mongo成品日志
                        PB_JobBookingDetailed pbdata = new PB_JobBookingDetailed();
                        pbdata.Id = IdHelper.GetId();
                        pbdata.No = item.Id;
                        pbdata.Nums = Convert.ToDouble(d);
                        pbdata.DeptId = deptdata.DetpId;
                        pbdata.OperationUserId = _operator.UserId;
                        pbdata.OperationUserName = bdata.RealName;
                        pbdata.OperationTime = DateTime.Now;
                        pbdata.Type = 4;
                        pbdata.OldOrNew = 1;
                        pbdata.PrinterId = data.PrinterId;
                        pbdetailed.Add(pbdata);
                    }
                }
            }
            MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
            listdata.GroupBy(x => new { x.Id, x.No, x.Name, x.TypeName, x.Date, x.Dept, x.QrCode, x.Type, x.Status, x.Printer }).Select(x => new
            {
                Id = x.Key.Id,
                No = x.Key.No,
                Name = x.Key.Name,
                TypeName = x.Key.TypeName,
                Date = x.Key.Date,
                Dept = x.Key.Dept,
                QrCode = x.Key.QrCode,
                Type = x.Key.Type,
                Status = x.Key.Status,
                Printer = x.Key.Printer
            }).ToList();
            //插入mongo队列
            await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);
            //插入mongo报工操作明细
            await mongo.InsertManyAsync<PB_JobBookingDetailed>(JobBookingOperation, pbdetailed);
            //插入包明细
            await Db.InsertAsync<PB_PackListInfo>(listinfo);
            //插入包信息
            await Db.InsertAsync<PB_PackList>(listpack);
            //插入包数量信息
            await Db.InsertAsync<PB_PackMaterialCount>(PackMaterialCountList);

            //统计完插入报工明细表二维码信息
            await Db.InsertAsync(listcode);
        }

        /// <summary>
        /// 收货单物料二维码打印(推送包码和成品码)
        /// </summary>
        /// <param name="data"></param>
        /// <param name="_mongodbOptions"></param>
        /// <param name="_redisOptions"></param>
        /// <returns></returns>
        [Transactional]
        public async Task RecDetailPrintListAsync(RecDetailPrintDTO data, MongoDBOptions _mongodbOptions, RedisOptions _redisOptions)
        {
            //先查询要打印的物料信息
            Expression<Func<TD_RecDetail, PB_Material, Base_Department, PB_MaterialType, PB_Supplier, RecDetailPrintDataDTO>> select = (a, b, c, d, e) => new RecDetailPrintDataDTO
            {
                Id = a.Id,
                RecId = a.RecId,
                MaterialId = a.MaterialId,
                RecNum = a.RecNum,
                MaterialCode = b.Code,
                MaterialName = b.Name,
                MaterialSpec = b.Spec,
                IsNumber = b.IsNumber,
                DeptId = b.DeptId,
                DeptName = c.Name,
                MaterialType = d.Name,
                PackageNum = b.PackageNum,
                MaxPackageNum = b.MaxPackageNum,
                IsProduct = b.IsProduct,
                ProductCode = b.ProductCode,
                IsSingle = b.IsSingle,
                IsMine = b.IsMine,
                SupplierName = e.Name,
                IsSpec = b.IsSpec,
                IsStandard = b.IsStandard
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<TD_RecDetail>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<Base_Department>() on b.DeptId equals c.Id into bc
                    from c in bc.DefaultIfEmpty()
                    join d in Db.GetIQueryable<PB_MaterialType>() on b.MaterialTypeId equals d.Id into bd
                    from d in bd.DefaultIfEmpty()
                    join e in Db.GetIQueryable<PB_Supplier>() on a.Id equals e.Id into ae
                    from e in ae.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d, e);
            var listD = await q.Where(x => data.liststr.Contains(x.Id)).ToListAsync();
            if (listD.Count == 0)
            {
                throw new BusException("请检查数据的正确性");
            }

            //时间戳
            string timestamp = GetTimeStamp();
            //推送队列物料批次
            string strguid = Guid.NewGuid().ToString("N");

            //推送队列包批次
            string packguid = Guid.NewGuid().ToString("N");

            //实例化Redis操作类
            _redisOptions.DbChannel = (int)Redis_Type.redis6;
            RedisSetHelper redis = new RedisSetHelper(_redisOptions);
            List<PB_PackList> listpack = new List<PB_PackList>();
            List<PB_PackListInfo> listinfo = new List<PB_PackListInfo>();
            List<PrintQueue> listdata = new List<PrintQueue>();
            List<PB_PackMaterialCount> PackMaterialCountList = new List<PB_PackMaterialCount>();
            List<PB_JobBookingQrCode> listcode = new List<PB_JobBookingQrCode>();
            List<PB_JobBookingDetailed> pbdetailed = new List<PB_JobBookingDetailed>();
            Base_User bdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            //获取收货单信息
            TD_Receiving Receiving = await Db.GetIQueryable<TD_Receiving>().Where(x => x.Id == data.recid).FirstOrDefaultAsync();

            OutBillOrderDTO OutBillOrder = new OutBillOrderDTO();

            //收货单是外协成品收货时,获取收货单对应外协订单
            if (Receiving.Type == "HalfProduct")
            {
                //先查询要打印的物料信息
                Expression<Func<PB_OutsourcingBillReturnDetail, PB_OutsourcingBill, PB_ProductionOrder, PB_DesignList, OutBillOrderDTO>> halfselect = (a, b, c, d) => new OutBillOrderDTO
                {
                    RecId = a.RecId,
                    ProjectId = d.ProjectId,
                    BuildingNumberID = d.BuildingNumberID
                };
                halfselect = halfselect.BuildExtendSelectExpre();
                var halfq = from a in Db.GetIQueryable<PB_OutsourcingBillReturnDetail>().AsExpandable()
                            join b in Db.GetIQueryable<PB_OutsourcingBill>() on a.ParentId equals b.Id into ab
                            from b in ab.DefaultIfEmpty()
                            join c in Db.GetIQueryable<PB_ProductionOrder>() on b.RefCode equals c.Id into bc
                            from c in bc.DefaultIfEmpty()
                            join d in Db.GetIQueryable<PB_DesignList>() on c.DesignId equals d.Id into cd
                            from d in cd.DefaultIfEmpty()
                            select @halfselect.Invoke(a, b, c, d);
                OutBillOrder = await halfq.Where(x => x.RecId == data.recid).FirstOrDefaultAsync();
                if (!OutBillOrder.IsNullOrEmpty())
                {
                    if (!OutBillOrder.ProjectId.IsNullOrEmpty())
                    {
                        PB_Project Project = await Db.GetIQueryable<PB_Project>().Where(x => x.Id == OutBillOrder.ProjectId).FirstOrDefaultAsync();

                        PB_Buildingnumber Buildingnumber = await Db.GetIQueryable<PB_Buildingnumber>().Where(x => x.Id == OutBillOrder.BuildingNumberID).FirstOrDefaultAsync();

                        OutBillOrder.ProjectName = Project == null ? "" : Project.Name;
                        OutBillOrder.BuildingNumberName = Buildingnumber == null ? "" : Buildingnumber.Buildingnumber;
                    }
                }
            }

            var deptdata = await _opdept.GetOperatorDept();
            //判断是否是是自动打包，否
            if (data.IsPushQueue == false)
            {
                foreach (var item in listD)
                {
                    if (item.IsSingle == true)
                    {
                        PrintQueue pq = new PrintQueue();
                        PB_JobBookingQrCode jkcode = new PB_JobBookingQrCode();

                        string jobcodeId = IdHelper.GetId();   //成品档案表ID
                        pq.Id = IdHelper.GetId();
                        pq.Name = item.MaterialName;
                        pq.Date = DateTime.Now.ToString("yyyy-MM-dd");
                        pq.Dept = item.IsMine == true ? deptdata.DeptName : item.SupplierName;
                        if (RedisSetHelper.Exists("QualityTestingNumber"))
                        {
                            string thedate = DateTime.Now.ToString("yyyy-MM-dd");
                            if (redis.GetString("QualityTestingTime") == thedate)
                            {
                                redis.SetString("QualityTestingNumber", (Convert.ToInt32(redis.GetString("QualityTestingNumber")) + 1).ToString());
                                pq.No = jobcodeId + "," + redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                            }
                            else
                            {
                                redis.SetString("QualityTestingTime", thedate);
                                redis.SetString("QualityTestingNumber", "1");
                                pq.No = jobcodeId + "," + redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                            }
                        }
                        else
                        {
                            redis.SetString("QualityTestingNumber", "0");
                        }
                        pq.QrCode = h_Material + "," + item.MaterialId;
                        pq.TypeName = item.MaterialSpec;
                        pq.Type = Skill_Type.Statistics.ToString();
                        pq.Status = item.RecNum.ToString();
                        pq.Printer = data.MaterialPrinterId;
                        pq.IsProduct = item.IsProduct;
                        pq.BatchNumber = strguid;
                        pq.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                        pq.JobCount = 1;
                        if (Receiving.Type == "HalfProduct")
                        {
                            pq.ProjectName = OutBillOrder == null ? "" : OutBillOrder.ProjectName;
                            pq.BuildingNumberName = OutBillOrder == null ? "" : OutBillOrder.BuildingNumberName;
                        }
                        else
                        {
                            pq.ProjectName = "";
                            pq.BuildingNumberName = "";
                        }
                        pq.IsStandard = item.IsStandard == false ? 0 : 1;
                        listdata.Add(pq);
                        jkcode.Id = jobcodeId;
                        jkcode.QrCode = h_Material + "," + item.MaterialId;
                        jkcode.MaterialId = item.MaterialId;
                        jkcode.MaterialName = item.MaterialName;
                        jkcode.OldOrNew = 1;
                        jkcode.RecId = data.recid;
                        jkcode.PackStatus = 0;
                        listcode.Add(jkcode);
                        PB_JobBookingDetailed pbdata = new PB_JobBookingDetailed();
                        pbdata.Id = IdHelper.GetId();
                        pbdata.No = item.Id;
                        pbdata.Nums = 1;
                        pbdata.DeptId = deptdata.DetpId;
                        pbdata.OperationUserId = _operator.UserId;
                        pbdata.OperationUserName = bdata.RealName;
                        pbdata.OperationTime = DateTime.Now;
                        pbdata.Type = 4;
                        pbdata.OldOrNew = 1;
                        pbdata.PrinterId = data.MaterialPrinterId;
                        pbdetailed.Add(pbdata);
                    }
                    else
                    {
                        if (item.IsNumber == true)
                        {
                            for (int i = 0; i < item.RecNum; i++)
                            {
                                PrintQueue pq = new PrintQueue();
                                PB_JobBookingQrCode jkcode = new PB_JobBookingQrCode();

                                string jobcodeId = IdHelper.GetId();   //成品档案表ID
                                pq.Id = IdHelper.GetId();
                                pq.Name = item.MaterialName;
                                pq.Date = DateTime.Now.ToString("yyyy-MM-dd");
                                pq.Dept = item.IsMine == true ? deptdata.DeptName : item.SupplierName;
                                if (RedisSetHelper.Exists("QualityTestingNumber"))
                                {
                                    string thedate = DateTime.Now.ToString("yyyy-MM-dd");
                                    if (redis.GetString("QualityTestingTime") == thedate)
                                    {
                                        redis.SetString("QualityTestingNumber", (Convert.ToInt32(redis.GetString("QualityTestingNumber")) + 1).ToString());
                                        pq.No = jobcodeId + "," + redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                        jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                    }
                                    else
                                    {
                                        redis.SetString("QualityTestingTime", thedate);
                                        redis.SetString("QualityTestingNumber", "1");
                                        pq.No = jobcodeId + "," + redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                        jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                    }
                                }
                                else
                                {
                                    redis.SetString("QualityTestingNumber", "0");
                                }
                                pq.QrCode = h_FinishedProduct + "," + jobcodeId;
                                pq.TypeName = item.MaterialSpec;
                                pq.Type = Skill_Type.Statistics.ToString();
                                pq.Status = "0";
                                pq.Printer = data.MaterialPrinterId;
                                pq.IsProduct = item.IsProduct;
                                pq.BatchNumber = strguid;
                                pq.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                                pq.JobCount = item.RecNum;
                                if (Receiving.Type == "HalfProduct")
                                {
                                    pq.ProjectName = OutBillOrder == null ? "" : OutBillOrder.ProjectName;
                                    pq.BuildingNumberName = OutBillOrder == null ? "" : OutBillOrder.BuildingNumberName;
                                }
                                else
                                {
                                    pq.ProjectName = "";
                                    pq.BuildingNumberName = "";
                                }
                                pq.IsStandard = item.IsStandard == false ? 0 : 1;
                                listdata.Add(pq);
                                jkcode.Id = jobcodeId;
                                jkcode.QrCode = h_FinishedProduct + "," + jobcodeId;
                                jkcode.MaterialId = item.MaterialId;
                                jkcode.MaterialName = item.MaterialName;
                                jkcode.OldOrNew = 1;
                                jkcode.RecId = data.recid;
                                jkcode.PackStatus = 0;
                                listcode.Add(jkcode);
                            }
                            PB_JobBookingDetailed pbdata = new PB_JobBookingDetailed();
                            pbdata.Id = IdHelper.GetId();
                            pbdata.No = item.Id;
                            pbdata.Nums = item.RecNum;
                            pbdata.DeptId = deptdata.DetpId;
                            pbdata.OperationUserId = _operator.UserId;
                            pbdata.OperationUserName = bdata.RealName;
                            pbdata.OperationTime = DateTime.Now;
                            pbdata.Type = 4;
                            pbdata.OldOrNew = 1;
                            pbdata.PrinterId = data.MaterialPrinterId;
                            pbdetailed.Add(pbdata);
                        }
                        else
                        {
                            PrintQueue pq = new PrintQueue();
                            PB_JobBookingQrCode jkcode = new PB_JobBookingQrCode();

                            string jobcodeId = IdHelper.GetId();   //成品档案表ID
                            pq.Id = IdHelper.GetId();
                            pq.Name = item.MaterialName;
                            pq.Date = DateTime.Now.ToString("yyyy-MM-dd");
                            pq.Dept = item.IsMine == true ? deptdata.DeptName : item.SupplierName;
                            if (RedisSetHelper.Exists("QualityTestingNumber"))
                            {
                                string thedate = DateTime.Now.ToString("yyyy-MM-dd");
                                if (redis.GetString("QualityTestingTime") == thedate)
                                {
                                    redis.SetString("QualityTestingNumber", (Convert.ToInt32(redis.GetString("QualityTestingNumber")) + 1).ToString());
                                    pq.No = jobcodeId + "," + redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                    jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                }
                                else
                                {
                                    redis.SetString("QualityTestingTime", thedate);
                                    redis.SetString("QualityTestingNumber", "1");
                                    pq.No = jobcodeId + "," + redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                    jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                }
                            }
                            else
                            {
                                redis.SetString("QualityTestingNumber", "0");
                            }
                            pq.QrCode = h_FinishedProduct + "," + jobcodeId;
                            pq.TypeName = item.MaterialSpec;
                            pq.Type = Skill_Type.Statistics.ToString();
                            pq.Status = "0";
                            pq.Printer = data.MaterialPrinterId;
                            pq.IsProduct = item.IsProduct;
                            pq.BatchNumber = strguid;
                            pq.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                            pq.JobCount = 1;
                            if (Receiving.Type == "HalfProduct")
                            {
                                pq.ProjectName = OutBillOrder == null ? "" : OutBillOrder.ProjectName;
                                pq.BuildingNumberName = OutBillOrder == null ? "" : OutBillOrder.BuildingNumberName;
                            }
                            else
                            {
                                pq.ProjectName = "";
                                pq.BuildingNumberName = "";
                            }
                            pq.IsStandard = item.IsStandard == false ? 0 : 1;
                            listdata.Add(pq);
                            jkcode.Id = jobcodeId;
                            jkcode.QrCode = h_FinishedProduct + "," + jobcodeId;
                            jkcode.MaterialId = item.MaterialId;
                            jkcode.MaterialName = item.MaterialName;
                            jkcode.OldOrNew = 1;
                            jkcode.RecId = data.recid;
                            jkcode.PackStatus = 0;
                            listcode.Add(jkcode);
                            PB_JobBookingDetailed pbdata = new PB_JobBookingDetailed();
                            pbdata.Id = IdHelper.GetId();
                            pbdata.No = item.Id;
                            pbdata.Nums = 1;
                            pbdata.DeptId = deptdata.DetpId;
                            pbdata.OperationUserId = _operator.UserId;
                            pbdata.OperationUserName = bdata.RealName;
                            pbdata.OperationTime = DateTime.Now;
                            pbdata.Type = 4;
                            pbdata.OldOrNew = 1;
                            pbdata.PrinterId = data.MaterialPrinterId;
                            pbdetailed.Add(pbdata);
                        }
                    }
                }
            }
            else //判断是否是是自动打包，是
            {
                foreach (var item in listD)
                {
                    //推送队列物料批次
                    strguid = Guid.NewGuid().ToString("N");

                    //推送队列包批次
                    packguid = Guid.NewGuid().ToString("N");

                    //定义是否是大小包
                    bool bltrueorfalse = false;


                    //计算自动打包的数量
                    decimal d = 0;
                    if (data.IsMax == true)
                    {
                        if (item.IsSpec == true)
                        {
                            if (item.MaxPackageNum == 0 || item.MaxPackageNum.IsNullOrEmpty())
                            {
                                throw new BusException("请维护" + item.MaterialName + "的大包装数量!");
                            }
                            d = Math.Ceiling(Convert.ToDecimal(item.RecNum) / Convert.ToDecimal(item.MaxPackageNum));
                            bltrueorfalse = true;
                        }
                        else
                        {
                            if (item.PackageNum == 0 || item.PackageNum.IsNullOrEmpty())
                            {
                                throw new BusException("请维护" + item.MaterialName + "的小包装数量!");
                            }
                            d = Math.Ceiling(Convert.ToDecimal(item.RecNum) / Convert.ToDecimal(item.PackageNum));
                        }
                    }
                    else
                    {
                        if (item.PackageNum == 0 || item.PackageNum.IsNullOrEmpty())
                        {
                            throw new BusException("请维护" + item.MaterialName + "的小包装数量!");
                        }
                        d = Math.Ceiling(Convert.ToDecimal(item.RecNum) / Convert.ToDecimal(item.PackageNum));
                    }
                    //是否是序列化管理
                    if (item.IsNumber == true)
                    {
                        //TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                        //string sjtime = Convert.ToInt64(ts.TotalSeconds).ToString();
                        double? worknums = Convert.ToDouble(item.RecNum) + Convert.ToDouble(d);
                        double dcount = 0;
                        double dindex = 0;
                        //循环要生成的包数量
                        for (int i = 0; i < d; i++)
                        {
                            PrintQueue printdata = new PrintQueue();
                            PB_PackList packdata = new PB_PackList();
                            string dataName = "bag_" + timestamp + "_" + (i + 1);
                            string dataId = IdHelper.GetId();
                            dcount = bltrueorfalse == true ? Convert.ToDouble(item.MaxPackageNum) * (i + 1) : Convert.ToDouble(item.PackageNum) * (i + 1);
                            if (dcount <= item.RecNum)
                            {
                                dindex = bltrueorfalse == true ? Convert.ToDouble(item.MaxPackageNum) : Convert.ToDouble(item.PackageNum);
                            }
                            else
                            {
                                dindex = bltrueorfalse == true ? (item.RecNum - Convert.ToDouble(item.MaxPackageNum) * i) : (item.RecNum - Convert.ToDouble(item.PackageNum) * i);
                            }
                            for (int j = 0; j < dindex; j++)
                            {
                                if (j == 0)
                                {
                                    packdata.BoxName = item.MaterialName;
                                    packdata.MaterialId = item.MaterialId;
                                    printdata.Name = item.MaterialName;
                                    printdata.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                                    printdata.IsProduct = item.IsProduct;
                                }
                                PB_JobBookingQrCode jkcode = new PB_JobBookingQrCode();
                                string jobcodeId = IdHelper.GetId();   //成品档案表ID
                                if (RedisSetHelper.Exists("QualityTestingNumber"))
                                {
                                    string thedate = DateTime.Now.ToString("yyyy-MM-dd");
                                    if (redis.GetString("QualityTestingTime") == thedate)
                                    {
                                        redis.SetString("QualityTestingNumber", (Convert.ToInt32(redis.GetString("QualityTestingNumber")) + 1).ToString());
                                        jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                    }
                                    else
                                    {
                                        redis.SetString("QualityTestingTime", thedate);
                                        redis.SetString("QualityTestingNumber", "1");
                                        jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                    }
                                }
                                else
                                {
                                    redis.SetString("QualityTestingNumber", "0");
                                }
                                jkcode.Id = jobcodeId;
                                jkcode.QrCode = h_FinishedProduct + "," + jobcodeId;
                                jkcode.MaterialId = item.MaterialId;
                                jkcode.MaterialName = item.MaterialName;
                                jkcode.OldOrNew = 1;
                                jkcode.RecId = data.recid;
                                jkcode.PackId = dataId;
                                jkcode.PackStatus = 0;
                                listcode.Add(jkcode);

                                //包明细
                                PB_PackListInfo infodata = new PB_PackListInfo();
                                infodata.Id = IdHelper.GetId();
                                infodata.PackId = dataId;
                                infodata.JobBookingId = jobcodeId;
                                infodata.CreatorId = _operator.UserId;
                                infodata.CreatorName = bdata.RealName;
                                infodata.CreatorTime = DateTime.Now;
                                infodata.Deleted = false;
                                infodata.OldOrNew = 1;
                                listinfo.Add(infodata);
                                //成品码推送
                                PrintQueue materprint = new PrintQueue();
                                materprint.Id = IdHelper.GetId();
                                materprint.No = jobcodeId;
                                materprint.Name = item.MaterialName;
                                materprint.TypeName = item.MaterialType;
                                materprint.Date = DateTime.Now.ToString("yyyy-MM-dd");
                                materprint.Dept = deptdata.DeptName;
                                materprint.QrCode = h_FinishedProduct + "," + jobcodeId;
                                materprint.Type = Skill_Type.Statistics.ToString();
                                materprint.Status = "0";
                                materprint.Printer = data.MaterialPrinterId;
                                materprint.IsProduct = item.IsProduct;
                                materprint.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                                materprint.BatchNumber = strguid;
                                materprint.JobCount = worknums;
                                if (Receiving.Type == "HalfProduct")
                                {
                                    materprint.ProjectName = OutBillOrder == null ? "" : OutBillOrder.ProjectName;
                                    materprint.BuildingNumberName = OutBillOrder == null ? "" : OutBillOrder.BuildingNumberName;
                                }
                                else
                                {
                                    materprint.ProjectName = "";
                                    materprint.BuildingNumberName = "";
                                }
                                materprint.IsStandard = item.IsStandard == false ? 0 : 1;
                                listdata.Add(materprint);
                            }

                            PrintQueue pq = new PrintQueue();
                            pq.Id = IdHelper.GetId();
                            pq.No = dataId;
                            pq.Name = "分割线";
                            pq.TypeName = "--------------------------";
                            pq.Date = DateTime.Now.ToString("yyyy-MM-dd");
                            pq.Dept = "";
                            pq.QrCode = h_Pack + "," + dataId;
                            pq.Type = Skill_Type.Statistics.ToString();
                            pq.Status = "0";
                            pq.Printer = data.MaterialPrinterId;
                            pq.IsProduct = true;
                            pq.Code = "";
                            pq.BatchNumber = strguid;
                            pq.JobCount = worknums;
                            pq.ProjectName = "";
                            pq.BuildingNumberName = "";
                            pq.IsStandard = item.IsStandard == false ? 0 : 1;
                            listdata.Add(pq);

                            //包信息
                            packdata.Id = dataId;
                            packdata.DeptId = bdata.DepartmentId;
                            packdata.BoxNo = dataName;
                            packdata.Status = 1;
                            packdata.Type = 1;
                            packdata.State = true;
                            packdata.CreateTime = DateTime.Now;
                            packdata.CreatorId = _operator.UserId;
                            packdata.Deleted = false;
                            packdata.CreatorName = bdata.RealName;
                            packdata.Nums = dindex;
                            packdata.QrCode = h_Pack + "," + dataId;
                            packdata.WorkshopId = bdata.DepartmentId;
                            packdata.OldOrNew = 1;
                            packdata.PackageType = 0;
                            packdata.IsUnpacking = dindex == item.PackageNum ? false : true;
                            listpack.Add(packdata);

                            PB_PackMaterialCount PackMaterialCount = new PB_PackMaterialCount();
                            PackMaterialCount.Id = IdHelper.GetId();
                            PackMaterialCount.MaterialId = item.MaterialId;
                            PackMaterialCount.Nums = dindex;
                            PackMaterialCount.PackId = dataId;
                            PackMaterialCountList.Add(PackMaterialCount);

                            //推送包信息到打印队列
                            printdata.Id = IdHelper.GetId();
                            printdata.No = dataId;
                            printdata.Date = DateTime.Now.ToString("yyyy-MM-dd");
                            printdata.Dept = item.IsMine == true ? deptdata.DeptName : item.SupplierName;
                            printdata.BatchNumber = packguid;
                            printdata.QrCode = h_Pack + "," + dataId;
                            printdata.Type = Skill_Type.Package.ToString();
                            printdata.Status = dindex.ToString();
                            printdata.Printer = data.PrinterId;
                            printdata.TypeName = item.MaterialSpec;
                            printdata.JobCount = Convert.ToDouble(d);
                            if (Receiving.Type == "HalfProduct")
                            {
                                printdata.ProjectName = OutBillOrder == null ? "" : OutBillOrder.ProjectName;
                                printdata.BuildingNumberName = OutBillOrder == null ? "" : OutBillOrder.BuildingNumberName;
                            }
                            else
                            {
                                printdata.ProjectName = "";
                                printdata.BuildingNumberName = "";
                            }
                            printdata.IsStandard = item.IsStandard == false ? 0 : 1;
                            listdata.Add(printdata);
                        }

                        //生成成品记录
                        PB_JobBookingDetailed pbdata = new PB_JobBookingDetailed();
                        pbdata.Id = IdHelper.GetId();
                        pbdata.No = item.Id;
                        pbdata.Nums = item.RecNum;
                        pbdata.DeptId = deptdata.DetpId;
                        pbdata.OperationUserId = _operator.UserId;
                        pbdata.OperationUserName = bdata.RealName;
                        pbdata.OperationTime = DateTime.Now;
                        pbdata.Type = 4;
                        pbdata.OldOrNew = 1;
                        pbdata.PrinterId = data.PrinterId;
                        pbdetailed.Add(pbdata);
                    }
                    else
                    {
                        //TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                        //string sjtime = Convert.ToInt64(ts.TotalSeconds).ToString();
                        double dcount = 0;
                        double dindex = 0;
                        //循环要生成的包数量
                        for (int i = 0; i < d; i++)
                        {
                            dcount = Convert.ToDouble(item.PackageNum) * (i + 1);
                            if (dcount <= item.RecNum)
                            {
                                dindex = Convert.ToDouble(item.PackageNum);
                            }
                            else
                            {
                                dindex = item.RecNum - Convert.ToDouble(item.PackageNum) * i;
                            }
                            PB_JobBookingQrCode jkcode = new PB_JobBookingQrCode();
                            string dataId = IdHelper.GetId();
                            string jobcodeId = IdHelper.GetId();   //成品档案表ID
                            if (RedisSetHelper.Exists("QualityTestingNumber"))
                            {
                                string thedate = DateTime.Now.ToString("yyyy-MM-dd");
                                if (redis.GetString("QualityTestingTime") == thedate)
                                {
                                    redis.SetString("QualityTestingNumber", (Convert.ToInt32(redis.GetString("QualityTestingNumber")) + 1).ToString());
                                    jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                }
                                else
                                {
                                    redis.SetString("QualityTestingTime", thedate);
                                    redis.SetString("QualityTestingNumber", "1");
                                    jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                }
                            }
                            else
                            {
                                redis.SetString("QualityTestingNumber", "0");
                            }
                            jkcode.Id = jobcodeId;
                            jkcode.QrCode = h_FinishedProduct + "," + jobcodeId;
                            jkcode.MaterialId = item.MaterialId;
                            jkcode.MaterialName = item.MaterialName;
                            jkcode.OldOrNew = 1;
                            jkcode.RecId = data.recid;
                            jkcode.PackId = dataId;
                            jkcode.PackStatus = 0;
                            listcode.Add(jkcode);

                            //成品码推送
                            PrintQueue materprint = new PrintQueue();
                            materprint.Id = IdHelper.GetId();
                            materprint.No = jobcodeId;
                            materprint.Name = item.MaterialName;
                            materprint.TypeName = item.MaterialType;
                            materprint.Date = DateTime.Now.ToString("yyyy-MM-dd");
                            materprint.Dept = deptdata.DeptName;
                            materprint.QrCode = h_FinishedProduct + "," + jobcodeId;
                            materprint.Type = Skill_Type.Statistics.ToString();
                            materprint.Status = "0";
                            materprint.Printer = data.MaterialPrinterId;
                            materprint.IsProduct = item.IsProduct;
                            materprint.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                            materprint.BatchNumber = strguid;
                            materprint.JobCount = 2;
                            if (Receiving.Type == "HalfProduct")
                            {
                                materprint.ProjectName = OutBillOrder == null ? "" : OutBillOrder.ProjectName;
                                materprint.BuildingNumberName = OutBillOrder == null ? "" : OutBillOrder.BuildingNumberName;
                            }
                            else
                            {
                                materprint.ProjectName = "";
                                materprint.BuildingNumberName = "";
                            }
                            materprint.IsStandard = item.IsStandard == false ? 0 : 1;
                            listdata.Add(materprint);

                            

                            PrintQueue pq = new PrintQueue();
                            pq.Id = IdHelper.GetId();
                            pq.No = dataId;
                            pq.Name = "分割线";
                            pq.TypeName = "--------------------------";
                            pq.Date = DateTime.Now.ToString("yyyy-MM-dd");
                            pq.Dept = "";
                            pq.QrCode = h_Pack + "," + dataId;
                            pq.Type = Skill_Type.Statistics.ToString();
                            pq.Status = "0";
                            pq.Printer = data.MaterialPrinterId;
                            pq.IsProduct = true;
                            pq.Code = "";
                            pq.BatchNumber = strguid;
                            pq.JobCount = dindex;
                            listdata.Add(pq);


                            //生成包信息
                            PB_PackList packdata = new PB_PackList();
                            string dataName = "bag_" + timestamp + "_" + (i + 1);
                            
                            packdata.Id = dataId;
                            packdata.DeptId = bdata.DepartmentId;
                            packdata.BoxNo = dataName;
                            packdata.BoxName = item.MaterialName;
                            packdata.MaterialId = item.MaterialId;
                            packdata.Nums = dindex;
                            packdata.State = false;
                            packdata.QrCode = h_Pack + "," + dataId;
                            packdata.Type = 1;
                            packdata.CreatorId = _operator.UserId;
                            packdata.CreateTime = DateTime.Now;
                            packdata.CreatorName = bdata.RealName;
                            packdata.WorkshopId = bdata.DepartmentId;
                            packdata.Status = 1;
                            packdata.OldOrNew = 1;
                            packdata.PackageType = 0;
                            packdata.IsUnpacking = dindex == item.PackageNum ? false : true;
                            listpack.Add(packdata);

                            PB_PackMaterialCount PackMaterialCount = new PB_PackMaterialCount();
                            PackMaterialCount.Id = IdHelper.GetId();
                            PackMaterialCount.MaterialId = item.MaterialId;
                            PackMaterialCount.Nums = dindex;
                            PackMaterialCount.PackId = dataId;
                            PackMaterialCountList.Add(PackMaterialCount);

                            //生成包明细
                            PB_PackListInfo infodata = new PB_PackListInfo();
                            infodata.Id = IdHelper.GetId();
                            infodata.PackId = dataId;
                            infodata.JobBookingId = jobcodeId;
                            infodata.CreatorId = _operator.UserId;
                            infodata.CreatorName = bdata.RealName;
                            infodata.CreatorTime = DateTime.Now;
                            infodata.Deleted = false;
                            infodata.OldOrNew = 1;
                            listinfo.Add(infodata);

                            //包码推送
                            PrintQueue printdata = new PrintQueue();
                            printdata.Id = IdHelper.GetId();
                            printdata.No = dataId;
                            printdata.Name = item.MaterialName;
                            printdata.Date = DateTime.Now.ToString("yyyy-MM-dd");
                            printdata.Dept = item.IsMine == true ? deptdata.DeptName : item.SupplierName;
                            printdata.QrCode = h_Pack + "," + dataId;
                            printdata.Type = Skill_Type.Package.ToString();
                            printdata.Status = dindex.ToString();
                            printdata.Printer = data.PrinterId;
                            printdata.TypeName = item.MaterialSpec;
                            printdata.BatchNumber = packguid;
                            printdata.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                            printdata.IsProduct = item.IsProduct;
                            printdata.JobCount = Convert.ToDouble(d);
                            if (Receiving.Type == "HalfProduct")
                            {
                                printdata.ProjectName = OutBillOrder == null ? "" : OutBillOrder.ProjectName;
                                printdata.BuildingNumberName = OutBillOrder == null ? "" : OutBillOrder.BuildingNumberName;
                            }
                            else
                            {
                                printdata.ProjectName = "";
                                printdata.BuildingNumberName = "";
                            }
                            printdata.IsStandard = item.IsStandard == false ? 0 : 1;
                            listdata.Add(printdata);
                        }
                        //添加mongo成品日志
                        PB_JobBookingDetailed pbdata = new PB_JobBookingDetailed();
                        pbdata.Id = IdHelper.GetId();
                        pbdata.No = item.Id;
                        pbdata.Nums = Convert.ToDouble(d);
                        pbdata.DeptId = deptdata.DetpId;
                        pbdata.OperationUserId = _operator.UserId;
                        pbdata.OperationUserName = bdata.RealName;
                        pbdata.OperationTime = DateTime.Now;
                        pbdata.Type = 4;
                        pbdata.OldOrNew = 1;
                        pbdata.PrinterId = data.PrinterId;
                        pbdetailed.Add(pbdata);
                    }
                }
            }
            MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
            listdata.GroupBy(x => new { x.Id, x.No, x.Name, x.TypeName, x.Date, x.Dept, x.QrCode, x.Type, x.Status, x.Printer }).Select(x => new
            {
                Id = x.Key.Id,
                No = x.Key.No,
                Name = x.Key.Name,
                TypeName = x.Key.TypeName,
                Date = x.Key.Date,
                Dept = x.Key.Dept,
                QrCode = x.Key.QrCode,
                Type = x.Key.Type,
                Status = x.Key.Status,
                Printer = x.Key.Printer
            }).ToList();
            //插入mongo队列
            await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);
            //插入mongo报工操作明细
            await mongo.InsertManyAsync<PB_JobBookingDetailed>(JobBookingOperation, pbdetailed);
            //插入包明细
            await Db.InsertAsync<PB_PackListInfo>(listinfo);
            //插入包信息
            await Db.InsertAsync<PB_PackList>(listpack);

            //插入包数量信息
            await Db.InsertAsync<PB_PackMaterialCount>(PackMaterialCountList);

            //统计完插入报工明细表二维码信息
            await Db.InsertAsync(listcode);
        }

        /// <summary>
        /// 成品物料明细
        /// </summary>
        /// 增加分页逻辑  2022-02-18  赵锦涛
        /// <returns></returns>
        public async Task<PageResult<JobBookingMaterialDTO>> GetRecDetailJobBookingQrCodeAsync(PageInput<PB_JobBookingQrCodeConditionDTO> input)
        {
            var search = input.Search;
            string sql = @"select * from (select a.Id,a.MaterialId,a.MaterialName,b.`Code` as MaterialCode,a.QrCode from PB_JobBookingQrCode as a
left join PB_Material as b on a.MaterialId=b.Id
where a.RecId='{0}' and a.MaterialId='{1}' and b.IsSingle=1 LIMIT 1 ) as t
UNION ALL
select a.Id,a.MaterialId,a.MaterialName,b.`Code` as MaterialCode,a.QrCode from PB_JobBookingQrCode as a
left join PB_Material as b on a.MaterialId=b.Id
where a.RecId='{0}' and a.MaterialId='{1}' and b.IsSingle=0";
            string sqlMain = string.Format(sql, search.recid, search.MaterialId);
            List<JobBookingMaterialDTO> listdata = await Db.GetListBySqlAsync<JobBookingMaterialDTO>(sqlMain);
            int num = listdata.Count;
            var list = listdata
               .Skip((input.PageIndex - 1) * input.PageRows)
               .Take(input.PageRows).ToList();
            return new PageResult<JobBookingMaterialDTO> { Data = list, Total = num };
        }



        /// <summary>
        /// 成品物料补打
        /// </summary>
        /// <param name="data"></param>
        /// <param name="_mongodbOptions"></param>
        /// 推送队列增加批次    2022-03-01  赵锦涛
        /// <returns></returns>
        public async Task PrintRecDetailJobBookingQrCodeAsync(PB_DesignDetailPrintDataDTO data, MongoDBOptions _mongodbOptions)
        {
            var deptdata = await _opdept.GetOperatorDept();
            TD_Receiving recedata = await Db.GetIQueryable<TD_Receiving>().Where(x => x.Id == data.designdetailId).FirstOrDefaultAsync();

            OutBillOrderDTO OutBillOrder = new OutBillOrderDTO();

            //收货单是外协成品收货时,获取收货单对应外协订单
            if (recedata.Type == "HalfProduct")
            {
                //先查询要打印的物料信息
                Expression<Func<PB_OutsourcingBillReturnDetail, PB_OutsourcingBill, PB_ProductionOrder, PB_DesignList, OutBillOrderDTO>> halfselect = (a, b, c, d) => new OutBillOrderDTO
                {
                    RecId = a.RecId,
                    ProjectId = d.ProjectId,
                    BuildingNumberID = d.BuildingNumberID
                };
                halfselect = halfselect.BuildExtendSelectExpre();
                var halfq = from a in Db.GetIQueryable<PB_OutsourcingBillReturnDetail>().AsExpandable()
                            join b in Db.GetIQueryable<PB_OutsourcingBill>() on a.ParentId equals b.Id into ab
                            from b in ab.DefaultIfEmpty()
                            join c in Db.GetIQueryable<PB_ProductionOrder>() on b.RefCode equals c.Id into bc
                            from c in bc.DefaultIfEmpty()
                            join d in Db.GetIQueryable<PB_DesignList>() on c.DesignId equals d.Id into cd
                            from d in cd.DefaultIfEmpty()
                            select @halfselect.Invoke(a, b, c, d);
                OutBillOrder = await halfq.Where(x => x.RecId == data.designdetailId).FirstOrDefaultAsync();
                if (!OutBillOrder.IsNullOrEmpty())
                {
                    if (!OutBillOrder.ProjectId.IsNullOrEmpty())
                    {
                        PB_Project Project = await Db.GetIQueryable<PB_Project>().Where(x => x.Id == OutBillOrder.ProjectId).FirstOrDefaultAsync();

                        PB_Buildingnumber Buildingnumber = await Db.GetIQueryable<PB_Buildingnumber>().Where(x => x.Id == OutBillOrder.BuildingNumberID).FirstOrDefaultAsync();

                        OutBillOrder.ProjectName = Project == null ? "" : Project.Name;
                        OutBillOrder.BuildingNumberName = Buildingnumber == null ? "" : Buildingnumber.Buildingnumber;
                    }
                }
            }

            PB_Supplier suppdata = await Db.GetIQueryable<PB_Supplier>().Where(x => x.Id == recedata.SupId).FirstOrDefaultAsync();
            Expression<Func<PB_JobBookingQrCode, PB_Material, PB_MaterialType, Base_Department, PB_JobBookingQrCodeDTO>> select = (a, b, c, d) => new PB_JobBookingQrCodeDTO
            {
                MaterialCode = b.Code,
                MaterialTypeName = c.Name,
                DeptId = b.DeptId,
                DeptName = d.Name,
                IsProduct = b.IsProduct,
                ProductCode = b.ProductCode,
                MaterialSpec = b.Spec,
                IsMine = b.IsMine,
                IsStandard=b.IsStandard,
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_JobBookingQrCode>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_MaterialType>() on b.MaterialTypeId equals c.Id into bc
                    from c in bc.DefaultIfEmpty()
                    join d in Db.GetIQueryable<Base_Department>() on b.DeptId equals d.Id into bd
                    from d in bd.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d);
            List<PrintQueue> listdata = new List<PrintQueue>();
            //推送队列批次
            string timestamp = Guid.NewGuid().ToString("N");
            if (data.nums.Count >= 100)
            {
                PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == data.nums[0].ToString()).FirstOrDefaultAsync();

                var qdata = await q.Where(x => x.RecId == data.designdetailId && x.MaterialId == jobdata.MaterialId).ToListAsync();
                
                if (qdata.Count > 0)
                {
                    foreach (var item in qdata)
                    {
                        PrintQueue pq = new PrintQueue();
                        pq.Id = IdHelper.GetId();
                        pq.No = item.Id + "," + item.SerialNumber;
                        pq.Name = item.MaterialName;
                        pq.TypeName = item.MaterialSpec;
                        pq.Date = DateTime.Now.ToString("yyyy-MM-dd");
                        if (suppdata == null)
                        {
                            pq.Dept = deptdata.DeptName;
                        }
                        else
                        {
                            pq.Dept = item.IsMine == true ? deptdata.DeptName : suppdata.Name;
                        }
                        pq.QrCode = item.QrCode;
                        pq.Type = Skill_Type.Statistics.ToString();
                        pq.Status = "0";
                        pq.Printer = data.PrinterId;
                        pq.IsProduct = item.IsProduct;
                        pq.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                        pq.BatchNumber = timestamp;
                        pq.JobCount = qdata.Count;
                        if (recedata.Type == "HalfProduct")
                        {
                            pq.ProjectName = OutBillOrder == null ? "" : OutBillOrder.ProjectName;
                            pq.BuildingNumberName = OutBillOrder == null ? "" : OutBillOrder.BuildingNumberName;
                        }
                        else
                        {
                            //成品补打增加项目楼号是否标准间
                            pq.ProjectName = "";
                            pq.BuildingNumberName = "";
                        }
                        pq.IsStandard = item.IsStandard == false ? 0 : 1;
                        listdata.Add(pq);
                    }
                    MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
                    //插入mongo队列
                    await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);

                    TD_ReceComplement recdata = new TD_ReceComplement();
                    recdata.Id = IdHelper.GetId();
                    recdata.RecId = recedata.Id;
                    recdata.MaterialId = jobdata.MaterialId;
                    recdata.PackId = "";
                    recdata.ComplementDate = DateTime.Now;
                    recdata.ComplementUserId = _operator.UserId;
                    recdata.ComplementUserName = _operator.Property?.RealName;
                    recdata.ComplementNums = qdata.Count;
                    recdata.CreatorId = _operator.UserId;
                    recdata.CreateTime = DateTime.Now;
                    recdata.Deleted = false;
                    await Db.InsertAsync<TD_ReceComplement>(recdata);
                }
                else
                {
                    throw new BusException("请选择后打印");
                }
            }
            else
            {
                var qdata = await q.Where(x => x.RecId == data.designdetailId && data.nums.Contains(x.Id)).ToListAsync();
                if (qdata.Count > 0)
                {
                    string MaterialId = "";
                    foreach (var item in qdata)
                    {

                        var sql = "SELECT project.`Name`,buding.Buildingnumber FROM PB_JobBookingQrCode AS job LEFT JOIN PB_ProductionOrder AS orderdata ON job.OrderId = orderdata.Id  LEFT JOIN PB_DesignList AS List ON orderdata.DesignId = List.Id LEFT JOIN PB_Project AS project ON List.ProjectId = project.Id  LEFT JOIN PB_Buildingnumber AS buding ON List.BuildingNumberID = buding.Id WHERE  job.Id = '"+item.Id+"'";
                        List <JobProjectData> JobProjectData =await Db.GetListBySqlAsync<JobProjectData>(sql); 

                        PrintQueue pq = new PrintQueue();
                        pq.Id = IdHelper.GetId();
                        pq.No = item.Id + "," + item.SerialNumber;
                        pq.Name = item.MaterialName;
                        pq.TypeName = item.MaterialSpec;
                        pq.Date = DateTime.Now.ToString("yyyy-MM-dd");
                        if (suppdata == null)
                        {
                            pq.Dept = deptdata.DeptName;
                        }
                        else
                        {
                            pq.Dept = item.IsMine == true ? deptdata.DeptName : suppdata.Name;
                        }
                        pq.QrCode = item.QrCode;
                        pq.Type = Skill_Type.Statistics.ToString();
                        pq.Status = "0";
                        pq.Printer = data.PrinterId;
                        pq.IsProduct = item.IsProduct;
                        pq.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                        pq.BatchNumber = timestamp;
                        pq.JobCount = qdata.Count;
                        if (recedata.Type == "HalfProduct")
                        {
                            pq.ProjectName = OutBillOrder == null ? "" : OutBillOrder.ProjectName;
                            pq.BuildingNumberName = OutBillOrder == null ? "" : OutBillOrder.BuildingNumberName;
                        }
                        else
                        {
                            //成品补打增加项目楼号是否标准间
                            pq.ProjectName = JobProjectData.Count == 0 ? "" : JobProjectData[0].Name;
                            pq.BuildingNumberName = JobProjectData.Count == 0 ? "" : JobProjectData[0].Buildingnumber;
                        }
                        pq.IsStandard = item.IsStandard == false ? 0 : 1;
                        listdata.Add(pq);
                        MaterialId = item.MaterialId;
                    }
                    MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
                    //插入mongo队列
                    await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);

                    TD_ReceComplement recdata = new TD_ReceComplement();
                    recdata.Id = IdHelper.GetId();
                    recdata.RecId = recedata.Id;
                    recdata.MaterialId = MaterialId;
                    recdata.PackId = "";
                    recdata.ComplementDate = DateTime.Now;
                    recdata.ComplementUserId = _operator.UserId;
                    recdata.ComplementUserName = _operator.Property?.RealName;
                    recdata.ComplementNums = qdata.Count;
                    recdata.CreatorId = _operator.UserId;
                    recdata.CreateTime = DateTime.Now;
                    recdata.Deleted = false;
                    await Db.InsertAsync<TD_ReceComplement>(recdata);
                }
                else
                {
                    throw new BusException("请选择后打印");
                }
            }
        }

        /// <summary>
        /// 成品物料对应的包明细
        /// </summary>
        /// <param name="recid">收货单id</param>
        /// <param name="MaterialId">物料Id</param>
        /// 调整收货单混合包包码补打不显示包信息    2022-02-22  赵锦涛
        /// <returns></returns>
        public async Task<List<PB_PackListRecDTO>> GetRecPackListDataAsync(string recid, string MaterialId)
        {
            //string sqlMain = @"select c.Id,c.BoxName,a.MaterialId,d.`Name` as MaterialName,e.`Name` as MaterialTypeName,c.QrCode,f.`Name` as DeptName,a.RecId from PB_JobBookingQrCode as a join PB_PackListInfo as b on a.Id=b.JobBookingId join PB_PackList as c on b.PackId=c.Id join PB_Material as d on a.MaterialId=d.Id join  PB_MaterialType as e on d.MaterialTypeId=e.Id join Base_Department as f on c.DeptId=f.Id where a.RecId='"+ recid + "' and a.MaterialId='"+ MaterialId + "' GROUP BY c.Id,c.BoxName,a.MaterialId,d.`Name`,e.`Name`,c.QrCode,f.`Name`,a.RecId";
            string sqlMain = @"select t.*,b.BoxName,c.`Name` as MaterialName,d.`Name` as MaterialTypeName,b.QrCode,e.`Name` as DeptName from (select a.PackId as Id,a.RecId,a.MaterialId from pb_jobbookingqrcode as a where a.RecId='{0}' and a.MaterialId='{1}' group by a.PackId,a.RecId,a.MaterialId ) as t
left join pb_packlist as b on t.Id=b.Id
left join pb_material as c on t.MaterialId=c.Id
left join pb_materialtype as d on c.MaterialTypeId=d.Id
left join base_department as e on b.DeptId=e.Id ";
            string sql = string.Format(sqlMain, recid, MaterialId);
            var listdata = await Db.GetListBySqlAsync<PB_PackListRecDTO>(sql);
            if (listdata.Count > 0)
            {
                return listdata;
            }
            else
            {
                throw new BusException("暂无数据");
            }
        }

        /// <summary>
        /// 成品物料对应的包补打
        /// </summary>
        /// <param name="data"></param>
        /// <param name="_mongodbOptions"></param>
        /// 推送队列增加批次    2022-03-01  赵锦涛
        /// <returns></returns>
        public async Task PrintRecPackListDataAsync(PB_DesignDetailPrintDataDTO data, MongoDBOptions _mongodbOptions)
        {
            var deptdata = await _opdept.GetOperatorDept();

            TD_Receiving recedata = await Db.GetIQueryable<TD_Receiving>().Where(x => x.Id == data.designdetailId).FirstOrDefaultAsync();

            OutBillOrderDTO OutBillOrder = new OutBillOrderDTO();

            //收货单是外协成品收货时,获取收货单对应外协订单
            if (recedata.Type == "HalfProduct")
            {
                //先查询要打印的物料信息
                Expression<Func<PB_OutsourcingBillReturnDetail, PB_OutsourcingBill, PB_ProductionOrder, PB_DesignList, OutBillOrderDTO>> halfselect = (a, b, c, d) => new OutBillOrderDTO
                {
                    RecId = a.RecId,
                    ProjectId = d.ProjectId,
                    BuildingNumberID = d.BuildingNumberID
                };
                halfselect = halfselect.BuildExtendSelectExpre();
                var halfq = from a in Db.GetIQueryable<PB_OutsourcingBillReturnDetail>().AsExpandable()
                            join b in Db.GetIQueryable<PB_OutsourcingBill>() on a.ParentId equals b.Id into ab
                            from b in ab.DefaultIfEmpty()
                            join c in Db.GetIQueryable<PB_ProductionOrder>() on b.RefCode equals c.Id into bc
                            from c in bc.DefaultIfEmpty()
                            join d in Db.GetIQueryable<PB_DesignList>() on c.DesignId equals d.Id into cd
                            from d in cd.DefaultIfEmpty()
                            select @halfselect.Invoke(a, b, c, d);
                OutBillOrder = await halfq.Where(x => x.RecId == data.designdetailId).FirstOrDefaultAsync();
                if (!OutBillOrder.IsNullOrEmpty())
                {
                    if (!OutBillOrder.ProjectId.IsNullOrEmpty())
                    {
                        PB_Project Project = await Db.GetIQueryable<PB_Project>().Where(x => x.Id == OutBillOrder.ProjectId).FirstOrDefaultAsync();

                        PB_Buildingnumber Buildingnumber = await Db.GetIQueryable<PB_Buildingnumber>().Where(x => x.Id == OutBillOrder.BuildingNumberID).FirstOrDefaultAsync();

                        OutBillOrder.ProjectName = Project == null ? "" : Project.Name;
                        OutBillOrder.BuildingNumberName = Buildingnumber == null ? "" : Buildingnumber.Buildingnumber;
                    }
                }
            }


            PB_Supplier suppdata = await Db.GetIQueryable<PB_Supplier>().Where(x => x.Id == recedata.SupId).FirstOrDefaultAsync();

            string strid = string.Empty;
            foreach (var item in data.nums)
            {
                strid += "'" + item + "',";
            }
            strid = strid.Substring(0, strid.Length - 1);
            string sqlMain = @"SELECT a.Id,a.BoxName,a.MaterialId,d.`Code` as MaterialCode,d.Spec,d.ProductCode,d.IsProduct,d.`Name` as MaterialName,e.`Name` as MaterialTypeName,a.QrCode,f.`Name` as DeptName,c.RecId,a.Nums,d.IsMine, d.IsStandard from PB_PackList AS a left join PB_PackListInfo as b on a.Id=b.PackId left join PB_JobBookingQrCode as c on b.JobBookingId=c.Id left join PB_Material as d on a.MaterialId=d.Id left join PB_MaterialType as e on d.MaterialTypeId=e.Id left join Base_Department as f on a.DeptId=f.Id where c.RecId='" + data.designdetailId + "' and a.Id in (" + strid + ") GROUP BY a.Id,a.BoxName,a.MaterialId,d.`Code`,d.`Name`,d.Spec,d.ProductCode,d.IsProduct,e.`Name`,a.QrCode,f.`Name`,c.RecId,a.Nums,d.IsMine";
            var qdata = await Db.GetListBySqlAsync<PB_PackListRecDTO>(sqlMain);
            //推送批次
            string timestamp = Guid.NewGuid().ToString("N");
            if (qdata.Count > 0)
            {
                List<PrintQueue> listdata = new List<PrintQueue>();
                List<TD_ReceComplement> listComplement = new List<TD_ReceComplement>();
                foreach (var item in qdata)
                {
                    PrintQueue pq = new PrintQueue();
                    pq.Id = IdHelper.GetId();
                    pq.No = item.Id;
                    pq.Name = item.BoxName;
                    pq.TypeName = item.Spec;
                    pq.Date = DateTime.Now.ToString("yyyy-MM-dd");
                    if (suppdata == null)
                    {
                        pq.Dept = deptdata.DeptName;
                    }
                    else
                    {
                        pq.Dept = item.IsMine == true ? deptdata.DeptName : suppdata.Name;
                    }
                    pq.QrCode = item.QrCode;
                    pq.Type = Skill_Type.Package.ToString();
                    pq.Status = item.Nums.ToString();
                    pq.Printer = data.PrinterId;
                    pq.IsProduct = item.IsProduct == null ? true : item.IsProduct;
                    pq.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                    pq.BatchNumber = timestamp;
                    pq.JobCount = qdata.Count;
                    if (recedata.Type == "HalfProduct")
                    {
                        pq.ProjectName = OutBillOrder == null ? "" : OutBillOrder.ProjectName;
                        pq.BuildingNumberName = OutBillOrder == null ? "" : OutBillOrder.BuildingNumberName;
                    }
                    else
                    {
                        pq.ProjectName = "";
                        pq.BuildingNumberName = "";
                    }
                    pq.IsStandard = item.IsStandard == false ? 0 : 1;
                    listdata.Add(pq);

                    TD_ReceComplement trcdata = new TD_ReceComplement();
                    trcdata.Id = IdHelper.GetId();
                    trcdata.RecId = recedata.Id;
                    trcdata.MaterialId = item.MaterialId;
                    trcdata.PackId = item.Id;
                    trcdata.ComplementDate = DateTime.Now;
                    trcdata.ComplementUserId = _operator.UserId;
                    trcdata.ComplementUserName = _operator.Property?.RealName;
                    trcdata.ComplementNums = 1;
                    trcdata.CreatorId = _operator.UserId;
                    trcdata.CreateTime = DateTime.Now;
                    trcdata.Deleted = false;
                    listComplement.Add(trcdata);
                }
                MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
                //插入mongo队列
                await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);
                await Db.InsertAsync<TD_ReceComplement>(listComplement);
            }
            else
            {
                throw new BusException("请选择后打印");
            }
        }

        /// <summary>
        /// 收货单作废
        /// </summary>
        /// <param name="Id">收货单id</param>
        /// 收货单作废逻辑调整,增加非手工录入的收货单不能作废   2022-02-20  赵锦涛
        /// <returns></returns>
        [Transactional]
        public async Task CancelReceivingDataAsync(string Id)
        {
            TD_Receiving tdrecedata = await Db.GetIQueryable<TD_Receiving>().Where(x => x.Id == Id).FirstOrDefaultAsync();
            if (tdrecedata.Type != "HalfReceiving")
            {
                string sqlMain = string.Empty;
                //查询收货单上架的明细
                Expression<Func<PB_UpLoadList, IT_LocalDetail, PB_UpLoadListDTO>> select = (a, b) => new PB_UpLoadListDTO
                {
                    OldOrNew = b.OldOrNew,
                    localdetailId = b.Id
                };
                select = select.BuildExtendSelectExpre();
                var q = from a in Db.GetIQueryable<PB_UpLoadList>().AsExpandable()
                        join b in Db.GetIQueryable<IT_LocalDetail>() on new { MaterialId = a.MaterialId, LocalId = a.LocalId, PackId = a.PackId, JobId = a.JobId, Nums = a.Nums } equals new { MaterialId = b.MaterialId, LocalId = b.LocalId, PackId = b.PackId, JobId = b.JobId, Nums = b.Num } into ab
                        from b in ab.DefaultIfEmpty()
                        select @select.Invoke(a, b);
                List<PB_UpLoadListDTO> UpLoadList = await q.Where(x => x.ParentId == Id).ToListAsync();

                foreach (var item in UpLoadList)
                {
                    if (item.OldOrNew == 0)
                    {
                        sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + item.Nums + ",ScanNum=IFNULL(ScanNum,0)-" + item.Nums + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "';  ";
                    }
                    else if (item.OldOrNew == 1)
                    {
                        sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + item.Nums + ",ScanNum=IFNULL(ScanNum,0)-" + item.Nums + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "';  ";
                    }
                    sqlMain += @" delete from IT_LocalDetail where Id='" + item.localdetailId + "'; ";
                }

                //对库存明细表删除,库存汇总表减减
                sqlMain += @" update TD_Receiving set `Status`=5,UpdateTime=NOW() where Id='" + tdrecedata.Id + "'; ";
                sqlMain += @" update TD_RecDetail set InNum=0 where RecId='" + tdrecedata.Id + "'; ";

                List<PB_JobBookingQrCode> JobBookingQrCodeList = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.RecId == Id).ToListAsync();
                var packjob = JobBookingQrCodeList.GroupBy(x => new { x.PackId }).Select(x => new { PackId = x.Key.PackId }).ToList();
                List<string> packstrIds = new List<string>();
                foreach (var item in packjob)
                {
                    if (item.PackId != "")
                    {
                        packstrIds.Add(item.PackId);
                    }
                }
                if (packstrIds.Count > 0)
                {
                    List<PB_UnLoadList> unlist = await Db.GetIQueryable<PB_UnLoadList>().Where(x => packstrIds.Contains(x.PackId)).ToListAsync();
                    if (unlist.Count > 0)
                    {
                        throw new BusException("收货单对应的包有被使用不能作废");
                    }

                    //删除包和包明细
                    sqlMain += @"  update PB_PackList set Status=5 where Id in ('" + string.Join("','", packstrIds.ToArray()) + "'); ";
                }
                sqlMain += @" update PB_JobBookingQrCode set PackStatus=1 where RecId='" + tdrecedata.Id + "'; ";
                await ExecuteSqlAsync(sqlMain);
            }
            else
            {
                string sqlMain = string.Empty;
                List<IT_LocalDetail> LocalDetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.RecId == tdrecedata.Id).ToListAsync();
                foreach (var item in LocalDetail)
                {
                    sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "';  ";
                    sqlMain += @" update TD_RecDetail set InNum=IFNULL(InNum,0)-" + item.Num + " where RecId='" + tdrecedata.Id + "' and MaterialId='" + item.MaterialId + "'; ";
                }
                sqlMain += @" delete from IT_LocalDetail where RecId='" + tdrecedata.Id + "'; ";

                //对库存明细表删除,库存汇总表减减
                sqlMain += @" update TD_Receiving set `Status`=5,UpdateTime=NOW() where Id='" + tdrecedata.Id + "'; ";
                await ExecuteSqlAsync(sqlMain);
            }
        }


        #endregion

        #region  半成品入库

        /// <summary>
        /// 获取半成品信息
        /// 根据流转卡统计完的数量入库
        /// </summary>
        /// <param name="CirBillQrCode">流转卡二维码</param>
        /// <returns></returns>
        public async Task<CirBillMaterialDTO> GetCirBillMaterialDataAsync(string CirBillQrCode)
        {
            //获取流转卡Id
            string cirbillId = CirBillQrCode.Split(',')?[1].ToString();
            //获取半成品信息(流转卡的物料信息)
            Expression<Func<PB_CirculationBill, PB_Material, CirBillMaterialDTO>> select = (a, b) => new CirBillMaterialDTO
            {
                CirBillId = a.Id,
                MaterialId = a.MaterialId,
                MaterialCode = b.Code,
                MaterialName = b.Name,
                MaterialSpec = b.Spec,
                Nums = a.StatisticalQuantity,
                Type = a.Type
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_CirculationBill>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);
            CirBillMaterialDTO data= await q.Where(x => x.CirBillId == cirbillId && x.Type != 0).FirstOrDefaultAsync();
            if (data.Nums == 0)
            {
                throw new BusException("请先进行统计");
            }
            return data;
        }

        /// <summary>
        /// 半成品通知入库
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public async Task SaveCirBillStorDataAsync(CirBillStorData data)
        {
            //入库仓库Id
            string StorId = data.StorId;

            var memodata = data.ListMaterialData.GroupBy(x => new { x.MaterialName }).Select(x => new { MaterialName = x.Key.MaterialName }).ToList();
            string memo = string.Empty;
            foreach (var item in memodata)
            {
                memo += item.MaterialName + ",";
            }
            memo = memo.Substring(0, memo.Length - 1);

            //获取登录人信息
            Base_User bdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

            //建立通知入库单
            PB_WarehousingNotice pB_WarehousingNotice = new PB_WarehousingNotice();
            string dataId = IdHelper.GetId();
            pB_WarehousingNotice.Id = dataId;
            pB_WarehousingNotice.QrCode = h_WarehousingNotice + "," + dataId;
            pB_WarehousingNotice.DeptId = bdata.DepartmentId;
            pB_WarehousingNotice.CreatorName = bdata.RealName;
            pB_WarehousingNotice.CreateTime = DateTime.Now;
            pB_WarehousingNotice.CreatorId = _operator.UserId;
            pB_WarehousingNotice.Deleted = false;
            pB_WarehousingNotice.Type = 1;
            pB_WarehousingNotice.CustomerToexamine = 1;
            pB_WarehousingNotice.Memo = memo;
            pB_WarehousingNotice.StorId = StorId;
            await Db.InsertAsync<PB_WarehousingNotice>(pB_WarehousingNotice);

            List<PB_Material> listMaterial = await Db.GetIQueryable<PB_Material>().ToListAsync();

            //入库通知提交生成收货单  
            string RecId = IdHelper.GetId();

            double? TotalNum = 0;
            double? TotalAmt = 0;
            string billIds = string.Empty;

            List<TD_RecDetail> listRecDetail = new List<TD_RecDetail>();
            foreach (var item in data.ListMaterialData)
            {
                var itemdata = listMaterial.Where(x => x.Id == item.MaterialId).FirstOrDefault();
                TD_RecDetail rd = new TD_RecDetail();
                rd.Id = IdHelper.GetId();
                rd.RecId = RecId;
                rd.StorId = StorId;
                rd.MaterialId = item.MaterialId;
                rd.Price = Convert.ToDouble(itemdata.Price);
                rd.PlanNum = Convert.ToDouble(item.Nums);
                rd.RecNum = Convert.ToDouble(item.Nums);
                rd.InNum = 0;
                rd.Amount = Convert.ToDouble(itemdata.Price * item.Nums);
                rd.CreateTime = DateTime.Now;
                rd.CreatorId = _operator.UserId;
                rd.Deleted = false;
                rd.CirBillId = item.CirBillId;
                listRecDetail.Add(rd);
                TotalNum += item.Nums;
                TotalAmt += Convert.ToDouble(itemdata.Price * item.Nums);

                billIds += "'" + item.CirBillId + "',";
            }
            billIds = billIds.Substring(0, billIds.Length - 1);
            string sqlMain = @"update PB_CirculationBill set NoticeId='" + dataId + "' where Id in (" + billIds + ")";
            await ExecuteSqlAsync(sqlMain);

            TD_Receiving rdata = new TD_Receiving();
            rdata.Id = RecId;
            rdata.StorId = StorId;
            rdata.Code = GetTimeStamp();
            rdata.OrderTime = DateTime.Now;
            rdata.RecTime = DateTime.Now;
            rdata.Type = "HalfReceiving";
            rdata.RefCode = dataId;
            rdata.Status = 3;
            rdata.TotalNum = Convert.ToDouble(TotalNum);
            rdata.InNum = 0;
            rdata.TotalAmt = Convert.ToDouble(TotalAmt);
            rdata.ConfirmUserId = _operator.UserId;
            rdata.ConfirmTime = DateTime.Now;
            rdata.AuditUserId = _operator.UserId;
            rdata.AuditeTime = DateTime.Now;
            rdata.CreateTime = DateTime.Now;
            rdata.CreatorId = _operator.UserId;
            rdata.Deleted = false;
            rdata.QrCode = h_TdRe + "," + RecId;
            rdata.DeptId = bdata.DepartmentId;
            rdata.UpdateTime = DateTime.Now;

            await Db.InsertAsync<TD_RecDetail>(listRecDetail);
            await Db.InsertAsync<TD_Receiving>(rdata);

        }

        /// <summary>
        /// PDA根据收货单上架入库扫描流转单获取物料信息
        /// </summary>
        /// <param name="CirBillQrCode">流转卡二维码</param>
        /// <returns></returns>
        public async Task<CirBillMaterialRecDTO> GetCirBillMaterialRecDataAsync(string CirBillQrCode)
        {
            string cirbillId = CirBillQrCode.Split(',')?[1].ToString();
            Expression<Func<PB_CirculationBill, PB_Material, TD_RecDetail, CirBillMaterialRecDTO>> select = (a, b, c) => new CirBillMaterialRecDTO
            {
                CirBillId = a.Id,
                MaterialId = a.MaterialId,
                MaterialCode = b.Code,
                MaterialName = b.Name,
                MaterialSpec = b.Spec,
                Price = b.Price,
                storageId = b.storageId,
                Nums = c.RecNum,
                RecId = c.RecId
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_CirculationBill>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<TD_RecDetail>() on a.Id equals c.CirBillId into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);
            return await q.Where(x => x.CirBillId == cirbillId).FirstOrDefaultAsync();
        }

        #endregion

        #region 回货入库打码

        /// <summary>
        /// 回货入库打码
        /// </summary>
        /// <param name="data"></param>
        /// <param name="_mongodbOptions"></param>
        /// <param name="_redisOptions"></param>
        /// <returns></returns>
        [Transactional]
        public async Task PrintRecoveryListAsync(RecoveryMaterialDTO data, MongoDBOptions _mongodbOptions, RedisOptions _redisOptions)
        {
            Base_User bdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

            List<string> recdetailIds = new List<string>();
            foreach (var item in data.RecDetailList)
            {
                recdetailIds.Add(item.Id);
            }
            //先查询要打印的物料信息
            Expression<Func<TD_RecDetail, PB_Material, Base_Department, PB_MaterialType, PB_Supplier, RecDetailPrintDataDTO>> select = (a, b, c, d, e) => new RecDetailPrintDataDTO
            {
                Id = a.Id,
                RecId = a.RecId,
                MaterialId = a.MaterialId,
                RecNum = a.RecNum,
                MaterialCode = b.Code,
                MaterialName = b.Name,
                MaterialSpec = b.Spec,
                IsNumber = b.IsNumber,
                DeptId = b.DeptId,
                DeptName = c.Name,
                MaterialType = d.Name,
                PackageNum = b.PackageNum,
                MaxPackageNum = b.MaxPackageNum,
                IsProduct = b.IsProduct,
                ProductCode = b.ProductCode,
                IsSingle = b.IsSingle,
                IsMine = b.IsMine,
                SupplierName = e.Name,
                IsSpec = b.IsSpec
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<TD_RecDetail>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<Base_Department>() on b.DeptId equals c.Id into bc
                    from c in bc.DefaultIfEmpty()
                    join d in Db.GetIQueryable<PB_MaterialType>() on b.MaterialTypeId equals d.Id into bd
                    from d in bd.DefaultIfEmpty()
                    join e in Db.GetIQueryable<PB_Supplier>() on a.Id equals e.Id into ae
                    from e in ae.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d, e);
            var listD = await q.Where(x => x.RecId == data.RecId && recdetailIds.Contains(x.Id)).ToListAsync();

            //时间戳
            string timestamp = GetTimeStamp();

            List<PB_PackList> listpack = new List<PB_PackList>();
            List<PB_PackListInfo> listinfo = new List<PB_PackListInfo>();
            List<PrintQueue> listdata = new List<PrintQueue>();
            List<PB_JobBookingQrCode> listcode = new List<PB_JobBookingQrCode>();
            List<PB_JobBookingDetailed> pbdetailed = new List<PB_JobBookingDetailed>();

            //实例化Redis操作类
            _redisOptions.DbChannel = (int)Redis_Type.redis6;
            RedisSetHelper redis = new RedisSetHelper(_redisOptions);
            var deptdata = await _opdept.GetOperatorDept();

            //推送队列包批次
            string packguid = Guid.NewGuid().ToString("N");

            //推送打包数量
            double? dpackcount = 0;
            double? materialcount = 0;
            foreach (var item in listD)
            {
                //获取要打印的明细信息
                var itemdata = data.RecDetailList.Where(x => x.Id == item.Id).FirstOrDefault();
                //每包的包装数量
                double? PackNum = itemdata.RecoveryPackName;
                if (item.IsNumber == true)
                {
                    decimal d = Math.Ceiling(Convert.ToDecimal(item.RecNum) / Convert.ToDecimal(PackNum));
                    dpackcount += Convert.ToDouble(d);
                }
                else if (item.IsSingle == true)
                {
                    materialcount += 1;
                }
            }

            foreach (var item in listD)
            {
                //获取要打印的明细信息
                var itemdata = data.RecDetailList.Where(x => x.Id == item.Id).FirstOrDefault();
                //每包的包装数量
                double? PackNum = itemdata.RecoveryPackName;

                if (item.IsSingle == true)
                {
                    PrintQueue pq = new PrintQueue();
                    PB_JobBookingQrCode jkcode = new PB_JobBookingQrCode();

                    string jobcodeId = IdHelper.GetId();   //成品档案表ID
                    pq.Id = IdHelper.GetId();
                    pq.Name = item.MaterialName;
                    pq.Date = DateTime.Now.ToString("yyyy-MM-dd");
                    pq.Dept = item.IsMine == true ? deptdata.DeptName : item.SupplierName;
                    if (RedisSetHelper.Exists("QualityTestingNumber"))
                    {
                        string thedate = DateTime.Now.ToString("yyyy-MM-dd");
                        if (redis.GetString("QualityTestingTime") == thedate)
                        {
                            redis.SetString("QualityTestingNumber", (Convert.ToInt32(redis.GetString("QualityTestingNumber")) + 1).ToString());
                            pq.No = jobcodeId + "," + redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                            jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                        }
                        else
                        {
                            redis.SetString("QualityTestingTime", thedate);
                            redis.SetString("QualityTestingNumber", "1");
                            pq.No = jobcodeId + "," + redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                            jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                        }
                    }
                    else
                    {
                        redis.SetString("QualityTestingNumber", "0");
                    }
                    pq.QrCode = h_Material + "," + item.MaterialId;
                    pq.TypeName = item.MaterialSpec;
                    pq.Type = Skill_Type.Statistics.ToString();
                    pq.Status = PackNum.ToString();
                    pq.Printer = data.MaterialPrinterId;
                    pq.IsProduct = item.IsProduct;
                    pq.BatchNumber = packguid;
                    pq.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                    pq.JobCount = materialcount;
                    listdata.Add(pq);
                    jkcode.Id = jobcodeId;
                    jkcode.QrCode = h_Material + "," + item.MaterialId;
                    jkcode.MaterialId = item.MaterialId;
                    jkcode.MaterialName = item.MaterialName;
                    jkcode.OldOrNew = 1;
                    jkcode.RecId = data.RecId;
                    listcode.Add(jkcode);
                    PB_JobBookingDetailed pbdata = new PB_JobBookingDetailed();
                    pbdata.Id = IdHelper.GetId();
                    pbdata.No = item.Id;
                    pbdata.Nums = 1;
                    pbdata.DeptId = deptdata.DetpId;
                    pbdata.OperationUserId = _operator.UserId;
                    pbdata.OperationUserName = bdata.RealName;
                    pbdata.OperationTime = DateTime.Now;
                    pbdata.Type = 4;
                    pbdata.OldOrNew = 1;
                    pbdata.PrinterId = data.MaterialPrinterId;
                    pbdetailed.Add(pbdata);
                }
                else if (item.IsNumber == true)
                {
                    decimal d = Math.Ceiling(Convert.ToDecimal(item.RecNum) / Convert.ToDecimal(PackNum));
                    double dcount = 0;  //已生成包的物料数量
                    double dindex = 0; //每个包的包装数量

                    //循环要生成的包数量
                    for (int i = 0; i < d; i++)
                    {
                        //队列
                        PrintQueue printdata = new PrintQueue();
                        PB_PackList packdata = new PB_PackList();
                        string dataName = "bag_" + timestamp + "_" + (i + 1);
                        string dataId = IdHelper.GetId();
                        packdata.BoxName = item.MaterialName;
                        packdata.MaterialId = item.MaterialId;
                        printdata.Name = item.MaterialName;
                        printdata.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                        printdata.IsProduct = item.IsProduct;

                        dcount = Convert.ToDouble(PackNum * (i + 1));
                        if (dcount <= item.RecNum)
                        {
                            dindex = Convert.ToDouble(PackNum);
                        }
                        else
                        {
                            dindex = Convert.ToDouble(item.RecNum) - Convert.ToDouble(PackNum) * i;
                        }

                        //是否是序列化管理
                        if (item.IsNumber == true)
                        {
                            for (int j = 0; j < PackNum; j++)
                            {
                                PB_JobBookingQrCode jkcode = new PB_JobBookingQrCode();
                                string jobcodeId = IdHelper.GetId();   //成品档案表ID
                                if (RedisSetHelper.Exists("QualityTestingNumber"))
                                {
                                    string thedate = DateTime.Now.ToString("yyyy-MM-dd");
                                    if (redis.GetString("QualityTestingTime") == thedate)
                                    {
                                        redis.SetString("QualityTestingNumber", (Convert.ToInt32(redis.GetString("QualityTestingNumber")) + 1).ToString());
                                        jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                    }
                                    else
                                    {
                                        redis.SetString("QualityTestingTime", thedate);
                                        redis.SetString("QualityTestingNumber", "1");
                                        jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                    }
                                }
                                else
                                {
                                    redis.SetString("QualityTestingNumber", "0");
                                }
                                jkcode.Id = jobcodeId;
                                jkcode.QrCode = h_FinishedProduct + "," + jobcodeId;
                                jkcode.MaterialId = item.MaterialId;
                                jkcode.MaterialName = item.MaterialName;
                                jkcode.OldOrNew = 0;
                                jkcode.RecId = data.RecId;
                                jkcode.PackId = dataId;
                                listcode.Add(jkcode);

                                //包明细
                                PB_PackListInfo infodata = new PB_PackListInfo();
                                infodata.Id = IdHelper.GetId();
                                infodata.PackId = dataId;
                                infodata.JobBookingId = jobcodeId;
                                infodata.CreatorId = _operator.UserId;
                                infodata.CreatorName = bdata.RealName;
                                infodata.CreatorTime = DateTime.Now;
                                infodata.Deleted = false;
                                infodata.OldOrNew = 0;
                                listinfo.Add(infodata);
                            }
                        }

                        //包信息
                        packdata.Id = dataId;
                        packdata.DeptId = bdata.DepartmentId;
                        packdata.BoxNo = dataName;
                        packdata.Status = 1;
                        packdata.Type = 1;
                        packdata.State = true;
                        packdata.CreateTime = DateTime.Now;
                        packdata.CreatorId = _operator.UserId;
                        packdata.Deleted = false;
                        packdata.CreatorName = bdata.RealName;
                        packdata.Nums = dindex;
                        packdata.QrCode = h_Pack + "," + dataId;
                        packdata.WorkshopId = bdata.DepartmentId;
                        packdata.OldOrNew = 0;
                        packdata.PackageType = 0;
                        packdata.IsUnpacking = false;
                        listpack.Add(packdata);

                        //推送包信息到打印队列
                        printdata.Id = IdHelper.GetId();
                        printdata.No = dataId;
                        printdata.Date = DateTime.Now.ToString("yyyy-MM-dd");
                        printdata.Dept = item.IsMine == true ? deptdata.DeptName : item.SupplierName;
                        printdata.BatchNumber = packguid;
                        printdata.QrCode = h_Pack + "," + dataId;
                        printdata.Type = Skill_Type.Package.ToString();
                        printdata.Status = dindex.ToString();
                        printdata.Printer = data.PrinterId;
                        printdata.TypeName = item.MaterialSpec;
                        printdata.JobCount = Convert.ToDouble(dpackcount);
                        listdata.Add(printdata);

                    }
                    //添加mongo成品日志
                    PB_JobBookingDetailed pbdata = new PB_JobBookingDetailed();
                    pbdata.Id = IdHelper.GetId();
                    pbdata.No = item.Id;
                    pbdata.Nums = Convert.ToDouble(d);
                    pbdata.DeptId = deptdata.DetpId;
                    pbdata.OperationUserId = _operator.UserId;
                    pbdata.OperationUserName = bdata.RealName;
                    pbdata.OperationTime = DateTime.Now;
                    pbdata.Type = 4;
                    pbdata.OldOrNew = 0;
                    pbdata.PrinterId = data.PrinterId;
                    pbdetailed.Add(pbdata);
                }
            }

            MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
            listdata.GroupBy(x => new { x.Id, x.No, x.Name, x.TypeName, x.Date, x.Dept, x.QrCode, x.Type, x.Status, x.Printer }).Select(x => new
            {
                Id = x.Key.Id,
                No = x.Key.No,
                Name = x.Key.Name,
                TypeName = x.Key.TypeName,
                Date = x.Key.Date,
                Dept = x.Key.Dept,
                QrCode = x.Key.QrCode,
                Type = x.Key.Type,
                Status = x.Key.Status,
                Printer = x.Key.Printer
            }).ToList();
            //插入mongo队列
            await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);
            //插入mongo报工操作明细
            await mongo.InsertManyAsync<PB_JobBookingDetailed>(JobBookingOperation, pbdetailed);
            //插入包明细
            await Db.InsertAsync<PB_PackListInfo>(listinfo);
            //插入包信息
            await Db.InsertAsync<PB_PackList>(listpack);
            //统计完插入报工明细表二维码信息
            await Db.InsertAsync(listcode);
        }
        //待维打包上架入库
        public async Task SaveRecoveryWarehousingDto(RecoveryWarehousingDto data)
        {
            //获取用户信息
            Base_User bdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            //查询收货单是否审核过
            string ReceivingId = data.receqroce.Split(',')?[1].ToString();
            var recedata = await Db.GetIQueryable<TD_Receiving>().Where(x => x.Id == ReceivingId).FirstOrDefaultAsync();
            if(recedata==null) { throw new BusException("请扫描正确的收货单"); }
            if (recedata.Status == 3)
            {
                //获取货位id
                string LocationId = data.Locationqrcode.Split(',')?[1].ToString();
                //获取货位信息
                var Locationdata = await Db.GetIQueryable<PB_Location>().Where(x => x.Id == LocationId).FirstOrDefaultAsync();
                if (Locationdata.StorId != recedata.StorId)
                {
                    throw new BusException("请检查扫描的货位是否是收货单对应仓库下的货位");
                }
                //判断扫进来哪一种
                string packId = string.Empty;
                string materialId = string.Empty;
                string cirbillId = string.Empty;
                string JobId = string.Empty;
                string packmodel = data.packqrcode.Split(',')?[0].ToString();
                if (packmodel == "13")
                {
                    packId = data.packqrcode.Split(',')?[1].ToString();
                }
                else if (packmodel == "04")
                {
                    var model = data.packqrcode.Split(',');
                    if (model.Length > 2)
                    {
                        if (model.Length < 4)
                        {
                            throw new BusException("请扫描正确的二维码信息");
                        }
                        else
                        {
                            materialId = model?[3].ToString();
                        }
                    }
                    else
                    {
                        materialId = model?[1].ToString();
                    }
                    
                }
                else if (packmodel == "31")
                {
                    cirbillId = data.packqrcode.Split(',')?[1].ToString();
                }
                else if (packmodel == "14")
                {
                    JobId = data.packqrcode.Split(',')?[1].ToString();
                    //查询单个成品是否绑定包信息
                    PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == JobId).FirstOrDefaultAsync();
                    if (jobdata != null)
                    {
                        if (!jobdata.PackId.IsNullOrEmpty())
                        {
                            packmodel = "13";
                            packId = jobdata.PackId;
                        }
                    }
                }

                List<PB_Stock> StockList = new List<PB_Stock>();
                List<PB_StockLog> StockLogList = new List<PB_StockLog>();
                List<PB_UpLoadList> UpLoadListList = new List<PB_UpLoadList>();
                List<IT_LocalDetail> LocalDetailList = new List<IT_LocalDetail>();
                List<IT_LocalMaterial> LocalMaterialList = new List<IT_LocalMaterial>();
                List<PB_JobBookingQrCode> JobBookingQrCode = new List<PB_JobBookingQrCode>();
                string sqlMain = string.Empty;

                PB_WarehousingNotice noticedata = await Db.GetIQueryable<PB_WarehousingNotice>().Where(x => x.Id == recedata.RefCode).FirstOrDefaultAsync();
                if (packmodel == "13")
                {
                    //获取包信息
                    var packdata = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == packId).FirstOrDefaultAsync();
                    if (packdata != null)
                    {
                        if (packdata.Status == 0 || packdata.Status == 1)
                        {
                            throw new BusException("请扫描待上架的包");
                        }
                        //查询当前入库的包是否已入库
                        var detatildata = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.PackId == packId).ToListAsync();
                        //判断是否为混合包，不是混合包
                        if (packdata.PackageType == 0)
                        {
                            //获取物料信息
                            var Materialdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == packdata.MaterialId).FirstOrDefaultAsync();

                            //收货单类型等于采购收货
                            if (recedata.Type == "Purchase")
                            {
                                //修改包的入库通知单Id
                                sqlMain += @" update PB_PackList set NoticeId='" + recedata.RefCode + "' where Id='" + packId + "'; ";
                                //await ExecuteSqlAsync(sqlMain);
                                //修改包对应的成品码信息为收货单Id
                                Expression<Func<PB_JobBookingQrCode, PB_PackListInfo, PB_Material, PB_PackListInfoDetail>> select = (a, b, c) => new PB_PackListInfoDetail
                                {
                                    PackId = b.PackId,
                                    storageId = c.storageId,
                                    Price = c.Price
                                };
                                select = select.BuildExtendSelectExpre();
                                var q = from a in Db.GetIQueryable<PB_JobBookingQrCode>().AsExpandable()
                                        join b in Db.GetIQueryable<PB_PackListInfo>() on a.Id equals b.JobBookingId into ab
                                        from b in ab.DefaultIfEmpty()
                                        join c in Db.GetIQueryable<PB_Material>() on a.MaterialId equals c.Id into ac
                                        from c in ac.DefaultIfEmpty()
                                        select @select.Invoke(a, b, c);
                                var infodetail = await q.Where(x => x.PackId == packId && x.PurchaseId == recedata.OrderId).ToListAsync();
                                string jobids = string.Empty;
                                foreach (var item in infodetail)
                                {
                                    jobids += "'" + item.Id + "',";
                                }
                                jobids = jobids.Substring(0, jobids.Length - 1);
                                //修改成品码对应的收货单
                                sqlMain += @" update PB_JobBookingQrCode set RecId='" + recedata.Id + "' where Id in (" + jobids + ") and PurchaseId='" + recedata.OrderId + "'; ";
                                //await ExecuteSqlAsync(sqlMain);
                                string memoname = "";
                                if (noticedata.Memo.IsNullOrEmpty())
                                {
                                    memoname = packdata.BoxName;
                                }
                                else
                                {
                                    memoname = noticedata.Memo + "," + packdata.BoxName;
                                }
                                //修改入库通知单的说明字段
                                sqlMain += @"update PB_WarehousingNotice set Memo='" + memoname + "' where Id='" + recedata.RefCode + "'; ";
                            }
                            //退货收货
                            else if (recedata.Type == "ReceReturn")
                            {
                                //修改包的入库通知单Id
                                sqlMain += @" update PB_PackList set NoticeId='" + recedata.RefCode + "' where Id='" + packId + "'; ";
                                //修改包内成品对应的收货单
                                sqlMain += @" update PB_JobBookingQrCode set RecId='" + ReceivingId + "' where PackId='" + packId + "'; ";
                            }
                            else
                            {
                                List<PB_JobBookingQrCode> joblist = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.RecId == ReceivingId && x.PackId == packId).ToListAsync();
                                if (joblist.Count == 0)
                                {
                                    throw new BusException("请检查此包是否和收货单匹配");
                                }
                            }
                            TD_RecDetail RecDetail = await Db.GetIQueryable<TD_RecDetail>().Where(x => x.RecId == ReceivingId && x.MaterialId == packdata.MaterialId).FirstOrDefaultAsync();
                            if (RecDetail == null)
                            {
                                throw new BusException("请检查此包物料是否和收货单匹配");
                            }

                            var trueorfalse = await _check.GetTrueOrFalse(Materialdata.Id, Locationdata.StorId, LocationId);
                            if (trueorfalse.boolType == false)
                            {
                                throw new BusException("仓库物料正在盘点中禁止上架入库");
                            }
                            if (detatildata.Count == 0)
                            {
                                //插入库存
                                PB_Stock stockdata = new PB_Stock();
                                stockdata.Id = IdHelper.GetId();
                                stockdata.PackId = packId;
                                stockdata.StorId = Locationdata.StorId;
                                stockdata.LocationId = LocationId;
                                stockdata.StockNumber = packdata.Nums;
                                stockdata.MaterialId = packdata.MaterialId;
                                stockdata.CreatorId = _operator.UserId;
                                stockdata.CreatorName = bdata.RealName;
                                stockdata.CreateTime = DateTime.Now;
                                stockdata.OperatorId = _operator.UserId;
                                stockdata.OrderID = ReceivingId;
                                stockdata.Type = 1;
                                stockdata.OldOrNew = packdata.OldOrNew;
                                stockdata.CirBillId = "";
                                stockdata.JobId = "";
                                StockList.Add(stockdata);

                                //插入库日志表
                                PB_StockLog lodata = new PB_StockLog();
                                lodata.Id = IdHelper.GetId();
                                lodata.PackId = packId;
                                lodata.StorId = Locationdata.StorId;
                                lodata.LocationId = LocationId;
                                lodata.MaterialId = packdata.MaterialId;
                                lodata.StockNumber = packdata.Nums;
                                lodata.CreatorId = _operator.UserId;
                                lodata.CreatorName = bdata.RealName;
                                lodata.OperatorId = _operator.UserId;
                                lodata.OrderID = ReceivingId;
                                lodata.CreateTime = DateTime.Now;
                                lodata.Type = 1;
                                lodata.State = 0;
                                lodata.OldOrNew = packdata.OldOrNew;
                                lodata.CirBillId = "";
                                lodata.JobId = "";
                                StockLogList.Add(lodata);

                                //收货单物料明细对应的包信息
                                PB_UpLoadList updata = new PB_UpLoadList();
                                updata.Id = IdHelper.GetId();
                                updata.ParentId = ReceivingId;
                                updata.StorId = Locationdata.StorId;
                                updata.LocalId = LocationId;
                                updata.PackId = packId;
                                updata.MaterialId = packdata.MaterialId;
                                updata.Nums = packdata.Nums;
                                updata.CreatorId = _operator.UserId;
                                updata.CreatorRealName = bdata.RealName;
                                updata.CreateTime = DateTime.Now;
                                updata.Deleted = false;
                                updata.CirBillId = "";
                                updata.JobId = "";
                                UpLoadListList.Add(updata);

                                //库存明细表
                                IT_LocalDetail detdata = new IT_LocalDetail();
                                detdata.Id = IdHelper.GetId();
                                detdata.StorId = Locationdata.StorId;
                                detdata.LocalId = LocationId;
                                detdata.MaterialId = packdata.MaterialId;
                                detdata.MeasureId = Materialdata.storageId;
                                detdata.InTime = DateTime.Now;
                                detdata.CreateTime = DateTime.Now;
                                detdata.CreatorId = _operator.UserId;
                                detdata.Deleted = false;
                                detdata.Num = packdata.Nums;
                                detdata.BarCode = data.packqrcode;
                                detdata.PackId = packId;
                                detdata.Price = Materialdata.Price;
                                detdata.Amount = packdata.Nums * Materialdata.Price;
                                detdata.OldOrNew = 0;
                                detdata.RecId = ReceivingId;
                                detdata.JobId = "";
                                LocalDetailList.Add(detdata);

                                //查询货架上存放货物存汇总表是否存在
                                var materdata = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == packdata.MaterialId && x.StorId == Locationdata.StorId && x.LocalId == LocationId).FirstOrDefaultAsync();
                                if (materdata == null)
                                {
                                    //不存在新增
                                    IT_LocalMaterial itdata = new IT_LocalMaterial();
                                    itdata.Id = IdHelper.GetId();
                                    itdata.MaterialId = packdata.MaterialId;
                                    itdata.StorId = Locationdata.StorId;
                                    itdata.LocalId = LocationId;
                                    if (packdata.OldOrNew == 0)
                                    {
                                        itdata.Nums_O = Convert.ToDouble(packdata.Nums);
                                        itdata.Nums_N = 0;
                                    }
                                    else if (packdata.OldOrNew == 1)
                                    {
                                        itdata.Nums_O = 0;
                                        itdata.Nums_N = Convert.ToDouble(packdata.Nums);
                                    }
                                    itdata.CreatorId = _operator.UserId;
                                    itdata.CreateTime = DateTime.Now;
                                    itdata.Deleted = false;
                                    itdata.AreaId = Locationdata.AreaId;
                                    itdata.RackId = Locationdata.RackId;
                                    itdata.ScanNum = Convert.ToDouble(packdata.Nums);
                                    itdata.CheckNum = 0;
                                    LocalMaterialList.Add(itdata);
                                }
                                else
                                {
                                    if (detdata.OldOrNew == 0)
                                    {
                                        sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)+" + packdata.Nums + ",ScanNum=IFNULL(ScanNum,0)+'" + packdata.Nums + "' where StorId='" + Locationdata.StorId + "' and LocalId='" + LocationId + "' and MaterialId='" + packdata.MaterialId + "'; ";
                                    }
                                    else if (packdata.OldOrNew == 1)
                                    {
                                        sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + packdata.Nums + ",ScanNum=IFNULL(ScanNum,0)+'" + packdata.Nums + "' where StorId='" + Locationdata.StorId + "' and LocalId='" + LocationId + "' and MaterialId='" + packdata.MaterialId + "'; ";
                                    }
                                }

                                //修改物料审核前数量
                                sqlMain += @" update PB_Material set ScanNum=IFNULL(ScanNum,0)+" + packdata.Nums + " where Id='" + packdata.MaterialId + "'; ";

                                //修改包的状态为已入库
                                sqlMain += @" UPDATE PB_PackList SET  Status= '3',InStorTime=NOW() WHERE id='" + packId + "'; ";

                                //修改收货单的入库数量
                                sqlMain += @" update TD_RecDetail set InNum=IFNULL(InNum,0)+" + packdata.Nums + " where RecId='" + ReceivingId + "' and MaterialId='" + packdata.MaterialId + "' ;";

                            }
                            else
                            {
                                throw new BusException("不能重复入库");
                            }
                        }
                        else if (packdata.PackageType == 1)
                        {
                            List<PB_JobBookingQrCode> infodetail = new List<PB_JobBookingQrCode>();
                            //采购收货
                            if (recedata.Type == "Purchase")
                            {
                                //修改包的入库通知单Id
                                sqlMain += @" update PB_PackList set NoticeId='" + recedata.RefCode + "' where Id='" + packId + "'; ";
                                //await ExecuteSqlAsync(sqlMain);
                                infodetail = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.PackId == packId && x.PurchaseId == recedata.OrderId && x.RecId == ReceivingId).ToListAsync();
                                string jobids = string.Empty;
                                foreach (var item in infodetail)
                                {
                                    jobids += "'" + item.Id + "',";
                                }
                                jobids = jobids.Substring(0, jobids.Length - 1);
                                //修改成品码对应的收货单
                                sqlMain += @" update PB_JobBookingQrCode set RecId='" + recedata.Id + "' where Id in (" + jobids + ") and PurchaseId='" + recedata.OrderId + "'; ";
                                string memoname = "";
                                if (noticedata.Memo.IsNullOrEmpty())
                                {
                                    memoname = packdata.BoxName;
                                }
                                else
                                {
                                    memoname = noticedata.Memo + "," + packdata.BoxName;
                                }
                                //修改入库通知单的说明字段
                                sqlMain += @" update PB_WarehousingNotice set Memo='" + memoname + "' where Id='" + recedata.RefCode + "'; ";
                            }
                            //退货收货
                            else if (recedata.Type == "ReceReturn")
                            {
                                //修改包的入库通知单Id
                                sqlMain += @" update PB_PackList set NoticeId='" + recedata.RefCode + "' where Id='" + packId + "'; ";
                                //修改包内成品对应的收货单
                                sqlMain += @" update PB_JobBookingQrCode set RecId='" + ReceivingId + "' where PackId='" + packId + "'; ";
                                infodetail = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.PackId == packId).ToListAsync();
                            }
                            else
                            {
                                infodetail = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.PackId == packId && x.RecId == ReceivingId).ToListAsync();
                                if (infodetail.Count == 0)
                                {
                                    throw new BusException("请检查此包是否和收货单匹配");
                                }
                            }
                            List<string> infomaterlist = new List<string>();
                            var materialdata = infodetail.GroupBy(x => new { x.MaterialId, x.MaterialName }).Select(x => new { MaterialId = x.Key.MaterialId, MaterialName = x.Key.MaterialName }).ToList();
                            List<TD_RecDetail> RecDetaillist = await Db.GetIQueryable<TD_RecDetail>().Where(x => x.RecId == ReceivingId).ToListAsync();
                            //foreach (var item in materialdata)
                            //{
                            //    infomaterlist.Add(item.MaterialId);
                            //}
                            //List<PB_Material> materdatas = await Db.GetIQueryable<PB_Material>().Where(x => infomaterlist.Contains(x.Id)).ToListAsync();
                            foreach (var item in materialdata)
                            {
                                var itemdata = RecDetaillist.Where(x => x.MaterialId == item.MaterialId).FirstOrDefault();
                                if (itemdata == null)
                                {
                                    throw new BusException("请检查此包物料是否和收货单匹配");
                                }
                                var trueorfalse = await _check.GetTrueOrFalse(item.MaterialId, Locationdata.StorId, LocationId);
                                if (trueorfalse.boolType == false)
                                {
                                    throw new BusException("仓库" + item.MaterialName + "物料正在盘点中禁止上架入库");
                                }
                            }
                            if (detatildata.Count == 0)
                            {
                                //插入库存明细表
                                PB_StockLog lodata = new PB_StockLog();
                                lodata.Id = IdHelper.GetId();
                                lodata.PackId = packId;
                                lodata.StorId = Locationdata.StorId;
                                lodata.LocationId = LocationId;
                                lodata.MaterialId = "";
                                lodata.StockNumber = packdata.Nums;
                                lodata.CreatorId = _operator.UserId;
                                lodata.CreatorName = bdata.RealName;
                                lodata.OperatorId = _operator.UserId;
                                lodata.OrderID = ReceivingId;
                                lodata.CreateTime = DateTime.Now;
                                lodata.Type = 1;
                                lodata.State = 0;
                                lodata.OldOrNew = packdata.OldOrNew;
                                lodata.CirBillId = "";
                                lodata.JobId = "";
                                StockLogList.Add(lodata);
                                //List<PB_Stock> liststock = new List<PB_Stock>();
                                //List<IT_LocalDetail> listLocalDetail = new List<IT_LocalDetail>();
                                //List<IT_LocalMaterial> listLocalMaterial = new List<IT_LocalMaterial>();
                                var infolist = infodetail.GroupBy(x => new { x.MaterialId, x.OldOrNew, x.RecId }).Select(x => new { MaterialId = x.Key.MaterialId, OldOrNew = x.Key.OldOrNew, RecId = x.Key.RecId, Nums = x.Count() }).ToList();
                                foreach (var item in infolist)
                                {

                                    //插入货架上存放货物存明细表
                                    PB_Stock stockdata = new PB_Stock();
                                    stockdata.Id = IdHelper.GetId();
                                    stockdata.PackId = packId;
                                    stockdata.StorId = Locationdata.StorId;
                                    stockdata.LocationId = LocationId;
                                    stockdata.StockNumber = item.Nums;
                                    stockdata.MaterialId = item.MaterialId;
                                    stockdata.CreatorId = _operator.UserId;
                                    stockdata.CreatorName = bdata.RealName;
                                    stockdata.CreateTime = DateTime.Now;
                                    stockdata.OperatorId = _operator.UserId;
                                    stockdata.OrderID = ReceivingId;
                                    stockdata.Type = 1;
                                    stockdata.OldOrNew = packdata.OldOrNew;
                                    stockdata.CirBillId = "";
                                    stockdata.JobId = "";
                                    StockList.Add(stockdata);

                                    //收货单物料明细对应的包信息
                                    PB_UpLoadList updata = new PB_UpLoadList();
                                    updata.Id = IdHelper.GetId();
                                    updata.ParentId = ReceivingId;
                                    updata.StorId = Locationdata.StorId;
                                    updata.LocalId = LocationId;
                                    updata.PackId = packId;
                                    updata.Nums = item.Nums;
                                    updata.MaterialId = item.MaterialId;
                                    updata.CreatorId = _operator.UserId;
                                    updata.CreatorRealName = bdata.RealName;
                                    updata.CreateTime = DateTime.Now;
                                    updata.Deleted = false;
                                    updata.CirBillId = "";
                                    updata.JobId = "";
                                    UpLoadListList.Add(updata);

                                    //库存明细表
                                    IT_LocalDetail detdata = new IT_LocalDetail();
                                    detdata.Id = IdHelper.GetId();
                                    detdata.StorId = Locationdata.StorId;
                                    detdata.LocalId = LocationId;
                                    detdata.MaterialId = item.MaterialId;
                                    detdata.InTime = DateTime.Now;
                                    detdata.CreateTime = DateTime.Now;
                                    detdata.CreatorId = _operator.UserId;
                                    detdata.Deleted = false;
                                    detdata.Num = item.Nums;
                                    detdata.BarCode = data.packqrcode;
                                    detdata.PackId = packId;
                                    detdata.OldOrNew = packdata.OldOrNew;
                                    detdata.RecId = item.RecId;
                                    detdata.JobId = "";
                                    LocalDetailList.Add(detdata);

                                    //查询货架上存放货物存汇总表是否存在
                                    var materdata = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == item.MaterialId && x.StorId == Locationdata.StorId && x.LocalId == LocationId).FirstOrDefaultAsync();
                                    if (materdata == null)
                                    {
                                        //不存在新增
                                        IT_LocalMaterial itdata = new IT_LocalMaterial();
                                        itdata.Id = IdHelper.GetId();
                                        itdata.MaterialId = item.MaterialId;
                                        itdata.StorId = Locationdata.StorId;
                                        itdata.LocalId = LocationId;
                                        if (packdata.OldOrNew == 0)
                                        {
                                            itdata.Nums_O = item.Nums;
                                            itdata.Nums_N = 0;
                                        }
                                        else if (packdata.OldOrNew == 1)
                                        {
                                            itdata.Nums_O = 0;
                                            itdata.Nums_N = item.Nums;
                                        }
                                        itdata.CreatorId = _operator.UserId;
                                        itdata.CreateTime = DateTime.Now;
                                        itdata.Deleted = false;
                                        itdata.AreaId = Locationdata.AreaId;
                                        itdata.RackId = Locationdata.RackId;
                                        itdata.ScanNum = item.Nums;
                                        itdata.CheckNum = 0;
                                        LocalMaterialList.Add(itdata);
                                    }
                                    else
                                    {
                                        //存在修改

                                        if (item.OldOrNew == 0)
                                        {
                                            sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)+" + item.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + item.Nums + " where StorId='" + Locationdata.StorId + "' and LocalId='" + LocationId + "' and MaterialId='" + item.MaterialId + "'; ";
                                        }
                                        else if (item.OldOrNew == 1)
                                        {
                                            sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + item.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + item.Nums + " where StorId='" + Locationdata.StorId + "' and LocalId='" + LocationId + "' and MaterialId='" + item.MaterialId + "'; ";
                                        }
                                        //await ExecuteSqlAsync(sqlMain);
                                    }

                                    //修改物料审核前数量
                                    sqlMain += @" update PB_Material set ScanNum=IFNULL(ScanNum,0)+" + item.Nums + " where Id='" + item.MaterialId + "'; ";

                                    //修改收货单的入库数量
                                    sqlMain += @" update TD_RecDetail set InNum=IFNULL(InNum,0)+" + item.Nums + " where RecId='" + ReceivingId + "' and MaterialId='" + item.MaterialId + "'; ";
                                }
                                //修改包的状态为已入库
                                sqlMain += @" UPDATE PB_PackList SET  Status= '3',InStorTime=NOW() WHERE id='" + packId + "'; ";

                            }
                            else
                            {
                                throw new BusException("不能重复入库");
                            }
                            //await ExecuteSqlAsync(sqlMain);
                        }
                    }
                    else
                    {
                        throw new BusException("请扫描正确的要上架的包信息");
                    }
                }
                else if (packmodel == "04")  //扫描单个物料上架
                {
                    PB_Material materdatas = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == materialId).FirstOrDefaultAsync();
                    TD_RecDetail RecDetail = await Db.GetIQueryable<TD_RecDetail>().Where(x => x.RecId == ReceivingId && x.MaterialId == materdatas.Id).FirstOrDefaultAsync();
                  

                    if (RecDetail == null)
                    {
                        throw new BusException("请检查物料是否和收货单匹配");
                    }

                    if ((RecDetail.InNum + data.Nums) > RecDetail.RecNum)
                    {
                        throw new BusException("入库数量不能大于实收数量");
                    }

                    var trueorfalse = await _check.GetTrueOrFalse(materdatas.Id, Locationdata.StorId, LocationId);
                    if (trueorfalse.boolType == false)
                    {
                        throw new BusException("仓库物料正在盘点中禁止上架入库");
                    }
            

                    //插入库存明细表
                    PB_StockLog lodata = new PB_StockLog();
                    lodata.Id = IdHelper.GetId();
                    lodata.PackId = "";
                    lodata.StorId = Locationdata.StorId;
                    lodata.LocationId = LocationId;
                    lodata.MaterialId = materialId;
                    lodata.StockNumber = data.Nums;
                    lodata.CreatorId = _operator.UserId;
                    lodata.CreatorName = bdata.RealName;
                    lodata.OperatorId = _operator.UserId;
                    lodata.OrderID = ReceivingId;
                    lodata.CreateTime = DateTime.Now;
                    lodata.Type = 1;
                    lodata.State = 0;
                    lodata.OldOrNew = 0;
                    lodata.CirBillId = "";
                    lodata.JobId = "";
                    StockLogList.Add(lodata);

                    //收货单物料明细对应的包信息
                    PB_UpLoadList updata = new PB_UpLoadList();
                    updata.Id = IdHelper.GetId();
                    updata.ParentId = ReceivingId;
                    updata.StorId = Locationdata.StorId;
                    updata.LocalId = LocationId;
                    updata.PackId = "";
                    updata.MaterialId = materialId;
                    updata.Nums = data.Nums;
                    updata.CreatorId = _operator.UserId;
                    updata.CreatorRealName = bdata.RealName;
                    updata.CreateTime = DateTime.Now;
                    updata.Deleted = false;
                    updata.CirBillId = "";
                    updata.JobId = "";
                    UpLoadListList.Add(updata);

                    //库存明细表
                    IT_LocalDetail detdata = new IT_LocalDetail();
                    detdata.Id = IdHelper.GetId();
                    detdata.StorId = Locationdata.StorId;
                    detdata.LocalId = LocationId;
                    detdata.MaterialId = materialId;
                    detdata.MeasureId = materdatas.storageId;
                    detdata.InTime = DateTime.Now;
                    detdata.CreateTime = DateTime.Now;
                    detdata.CreatorId = _operator.UserId;
                    detdata.Deleted = false;
                    detdata.Num = data.Nums;
                    detdata.BarCode = data.packqrcode;
                    detdata.PackId = "";
                    detdata.Price = materdatas.Price;
                    detdata.Amount = data.Nums * materdatas.Price;
                    detdata.OldOrNew = 0;
                    detdata.RecId = ReceivingId;
                    detdata.JobId = "";
                    LocalDetailList.Add(detdata);
                    var materdata = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == materialId && x.StorId == Locationdata.StorId && x.LocalId == LocationId).FirstOrDefaultAsync();
                    if (materdata == null)
                    {
                        //不存在新增
                        IT_LocalMaterial itdata = new IT_LocalMaterial();
                        itdata.Id = IdHelper.GetId();
                        itdata.MaterialId = materialId;
                        itdata.StorId = Locationdata.StorId;
                        itdata.LocalId = LocationId;
                        itdata.Nums_N = 0;
                        itdata.Nums_O = Convert.ToDouble(data.Nums);
                        itdata.CreatorId = _operator.UserId;
                        itdata.CreateTime = DateTime.Now;
                        itdata.Deleted = false;
                        itdata.AreaId = Locationdata.AreaId;
                        itdata.RackId = Locationdata.RackId;
                        itdata.ScanNum = Convert.ToDouble(data.Nums);
                        itdata.CheckNum = 0;
                        LocalMaterialList.Add(itdata);
                    }
                    else
                    {
                        //存在修改
                        sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)+" + data.Nums + ",ScanNum=IFNULL(ScanNum,0)+'" + data.Nums + "' where StorId='" + Locationdata.StorId + "' and LocalId='" + LocationId + "' and MaterialId='" + materialId + "'; ";
                    }

                    //修改物料审核前数量
                    sqlMain += @" update PB_Material set ScanNum=IFNULL(ScanNum,0)+" + data.Nums + " where Id='" + materialId + "'; ";

                    //修改收货单的入库数量
                    sqlMain += @" update TD_RecDetail set InNum=IFNULL(InNum,0)+" + data.Nums + " where RecId='" + ReceivingId + "' and MaterialId='" + materialId + "'; ";
                }
                else if (packmodel == "31")
                {
                    Expression<Func<PB_CirculationBill, PB_Material, TD_RecDetail, CirBillMaterialRecDTO>> select = (a, b, c) => new CirBillMaterialRecDTO
                    {
                        CirBillId = a.Id,
                        MaterialId = a.MaterialId,
                        MaterialCode = b.Code,
                        MaterialName = b.Name,
                        MaterialSpec = b.Spec,
                        Price = b.Price,
                        storageId = b.storageId,
                        Nums = c.RecNum,
                        RecId = c.RecId
                    };
                    select = select.BuildExtendSelectExpre();
                    var q = from a in Db.GetIQueryable<PB_CirculationBill>().AsExpandable()
                            join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                            from b in ab.DefaultIfEmpty()
                            join c in Db.GetIQueryable<TD_RecDetail>() on a.Id equals c.CirBillId into ac
                            from c in ac.DefaultIfEmpty()
                            select @select.Invoke(a, b, c);
                    var materdatas = await q.Where(x => x.CirBillId == cirbillId).FirstOrDefaultAsync();
                    TD_RecDetail RecDetail = await Db.GetIQueryable<TD_RecDetail>().Where(x => x.RecId == ReceivingId && x.MaterialId == materdatas.MaterialId && x.CirBillId == cirbillId).FirstOrDefaultAsync();
                    if (RecDetail == null)
                    {
                        throw new BusException("请检查物料是否和收货单匹配");
                    }
                    if (RecDetail.InNum > 0)
                    {
                        throw new BusException("不能重复入库");
                    }

                    var trueorfalse = await _check.GetTrueOrFalse(materdatas.MaterialId, Locationdata.StorId, LocationId);
                    if (trueorfalse.boolType == false)
                    {
                        throw new BusException("仓库物料正在盘点中禁止上架入库");
                    }
                   

                    //插入库存明细表
                    PB_StockLog lodata = new PB_StockLog();
                    lodata.Id = IdHelper.GetId();
                    lodata.PackId = "";
                    lodata.StorId = Locationdata.StorId;
                    lodata.LocationId = LocationId;
                    lodata.MaterialId = materdatas.MaterialId;
                    lodata.StockNumber = materdatas.Nums;
                    lodata.CreatorId = _operator.UserId;
                    lodata.CreatorName = bdata.RealName;
                    lodata.OperatorId = _operator.UserId;
                    lodata.OrderID = ReceivingId;
                    lodata.CreateTime = DateTime.Now;
                    lodata.Type = 1;
                    lodata.State = 0;
                    lodata.OldOrNew = 0;
                    lodata.CirBillId = cirbillId;
                    lodata.JobId = "";
                    StockLogList.Add(lodata);

                    //收货单物料明细对应的包信息
                    PB_UpLoadList updata = new PB_UpLoadList();
                    updata.Id = IdHelper.GetId();
                    updata.ParentId = ReceivingId;
                    updata.StorId = Locationdata.StorId;
                    updata.LocalId = LocationId;
                    updata.PackId = "";
                    updata.MaterialId = materdatas.MaterialId;
                    updata.Nums = materdatas.Nums;
                    updata.CreatorId = _operator.UserId;
                    updata.CreatorRealName = bdata.RealName;
                    updata.CreateTime = DateTime.Now;
                    updata.Deleted = false;
                    updata.CirBillId = cirbillId;
                    updata.JobId = "";
                    UpLoadListList.Add(updata);

                    //库存明细表
                    IT_LocalDetail detdata = new IT_LocalDetail();
                    detdata.Id = IdHelper.GetId();
                    detdata.StorId = Locationdata.StorId;
                    detdata.LocalId = LocationId;
                    detdata.MaterialId = materdatas.MaterialId;
                    detdata.MeasureId = materdatas.storageId;
                    detdata.InTime = DateTime.Now;
                    detdata.CreateTime = DateTime.Now;
                    detdata.CreatorId = _operator.UserId;
                    detdata.Deleted = false;
                    detdata.Num = materdatas.Nums;
                    detdata.BarCode = data.packqrcode;
                    detdata.PackId = "";
                    detdata.Price = materdatas.Price;
                    detdata.Amount = materdatas.Nums * materdatas.Price;
                    detdata.OldOrNew = 0;
                    detdata.RecId = ReceivingId;
                    detdata.JobId = "";
                    LocalDetailList.Add(detdata);

                    //查询货架上存放货物存汇总表是否存在
                    var materdata = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == materdatas.MaterialId && x.StorId == Locationdata.StorId && x.LocalId == LocationId).FirstOrDefaultAsync();
                    if (materdata == null)
                    {
                        //不存在新增
                        IT_LocalMaterial itdata = new IT_LocalMaterial();
                        itdata.Id = IdHelper.GetId();
                        itdata.MaterialId = materdatas.MaterialId;
                        itdata.StorId = Locationdata.StorId;
                        itdata.LocalId = LocationId;
                        itdata.Nums_O = 0;
                        itdata.Nums_N = Convert.ToDouble(materdatas.Nums);
                        itdata.CreatorId = _operator.UserId;
                        itdata.CreateTime = DateTime.Now;
                        itdata.Deleted = false;
                        itdata.AreaId = Locationdata.AreaId;
                        itdata.RackId = Locationdata.RackId;
                        itdata.ScanNum = Convert.ToDouble(materdatas.Nums);
                        itdata.CheckNum = 0;
                        LocalMaterialList.Add(itdata);
                    }
                    else
                    {
                        //存在修改
                        sqlMain += @"update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + materdatas.Nums + ",ScanNum=IFNULL(ScanNum,0)+'" + materdatas.Nums + "' where StorId='" + Locationdata.StorId + "' and LocalId='" + LocationId + "' and MaterialId='" + materdatas.MaterialId + "'; ";
                    }

                    //修改物料审核前数量
                    sqlMain += @" update PB_Material set ScanNum=IFNULL(ScanNum,0)+" + materdatas.Nums + " where Id='" + materdatas.MaterialId + "'; ";
                    //修改收货单的入库数量
                    sqlMain += @" update TD_RecDetail set InNum=IFNULL(InNum,0)+" + materdatas.Nums + " where RecId='" + ReceivingId + "' and MaterialId='" + materdatas.MaterialId + "' and CirBillId='" + cirbillId + "'; ";
                }
                else if (packmodel == "14")
                {
                    //查询成品信息
                    PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == JobId).FirstOrDefaultAsync();
                    if (jobdata == null)
                    {
                        throw new BusException("请检查成品是否存在");
                    }
                    //查询成品物料与收货单物料是否匹配
                    TD_RecDetail RecDetail = await Db.GetIQueryable<TD_RecDetail>().Where(x => x.RecId == ReceivingId && x.MaterialId == jobdata.MaterialId).FirstOrDefaultAsync();
                    if (jobdata != null)
                    {
                        if (recedata.Type == "ReceReturn")
                        {
                            //修改单个成品对应的收货单
                            sqlMain += @" update PB_JobBookingQrCode set RecId='" + ReceivingId + "' where Id='" + JobId + "'; ";
                            //添加单个成品的入库通知
                            sqlMain += @" INSERT INTO PB_JobNotice(Id,JobId,NoticeId,RecId,CreatorId,CreateTime,Deleted) values ('" + IdHelper.GetId() + "','" + JobId + "','" + recedata.RefCode + "','" + ReceivingId + "','" + _operator.UserId + "',NOW(),0); ";
                        }
                        else
                        {
                            PB_JobNotice notice = await Db.GetIQueryable<PB_JobNotice>().Where(x => x.JobId == JobId && x.RecId == ReceivingId).FirstOrDefaultAsync();
                            if (notice == null)
                            {
                                throw new BusException("未通知入库的成品不能扫码上架");
                            }
                        }
                        IT_LocalDetail LocalDetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.JobId == JobId).FirstOrDefaultAsync();
                        if (LocalDetail != null)
                        {
                            throw new BusException("已入库不能重复入库");
                        }
                        if (!jobdata.PackId.IsNullOrEmpty())
                        {
                            throw new BusException("已打包的成品不能按单个成品入库");
                        }
                        if (RecDetail == null)
                        {
                            throw new BusException("请检查物料是否和收货单匹配");
                        }
                        if ((RecDetail.InNum + 1) > RecDetail.RecNum)
                        {
                            throw new BusException("入库数量不能大于收货数量");
                        }
                        var trueorfalse = await _check.GetTrueOrFalse(jobdata.MaterialId, Locationdata.StorId, LocationId);
                        if (trueorfalse.boolType == false)
                        {
                            throw new BusException("仓库物料正在盘点中禁止上架入库");
                        }
                      

                        //插入库存明细表
                        PB_StockLog lodata = new PB_StockLog();
                        lodata.Id = IdHelper.GetId();
                        lodata.PackId = "";
                        lodata.StorId = Locationdata.StorId;
                        lodata.LocationId = LocationId;
                        lodata.MaterialId = jobdata.MaterialId;
                        lodata.StockNumber = 1;
                        lodata.CreatorId = _operator.UserId;
                        lodata.CreatorName = bdata.RealName;
                        lodata.OperatorId = _operator.UserId;
                        lodata.OrderID = ReceivingId;
                        lodata.CreateTime = DateTime.Now;
                        lodata.Type = 1;
                        lodata.State = 0;
                        lodata.OldOrNew = 0;
                        lodata.CirBillId = "";
                        lodata.JobId = JobId;
                        StockLogList.Add(lodata);

                        //收货单物料明细对应的包信息
                        PB_UpLoadList updata = new PB_UpLoadList();
                        updata.Id = IdHelper.GetId();
                        updata.ParentId = ReceivingId;
                        updata.StorId = Locationdata.StorId;
                        updata.LocalId = LocationId;
                        updata.PackId = "";
                        updata.MaterialId = jobdata.MaterialId;
                        updata.Nums = 1;
                        updata.CreatorId = _operator.UserId;
                        updata.CreatorRealName = bdata.RealName;
                        updata.CreateTime = DateTime.Now;
                        updata.Deleted = false;
                        updata.CirBillId = "";
                        updata.JobId = JobId;
                        UpLoadListList.Add(updata);

                        PB_Material materdatas = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == jobdata.MaterialId).FirstOrDefaultAsync();

                        //库存明细表
                        IT_LocalDetail detdata = new IT_LocalDetail();
                        detdata.Id = IdHelper.GetId();
                        detdata.StorId = Locationdata.StorId;
                        detdata.LocalId = LocationId;
                        detdata.MaterialId = jobdata.MaterialId;
                        detdata.MeasureId = materdatas.storageId;
                        detdata.InTime = DateTime.Now;
                        detdata.CreateTime = DateTime.Now;
                        detdata.CreatorId = _operator.UserId;
                        detdata.Deleted = false;
                        detdata.Num = 1;
                        detdata.BarCode = data.packqrcode;
                        detdata.PackId = "";
                        detdata.Price = materdatas.Price;
                        detdata.Amount = materdatas.Price;
                        detdata.OldOrNew = 0;
                        detdata.RecId = ReceivingId;
                        detdata.JobId = JobId;
                        LocalDetailList.Add(detdata);

                        //查询货架上存放货物存汇总表是否存在
                        var materdata = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == jobdata.MaterialId && x.StorId == Locationdata.StorId && x.LocalId == LocationId).FirstOrDefaultAsync();
                        if (materdata == null)
                        {
                            if (jobdata.OldOrNew == 0)
                            {
                                //不存在新增
                                IT_LocalMaterial itdata = new IT_LocalMaterial();
                                itdata.Id = IdHelper.GetId();
                                itdata.MaterialId = jobdata.MaterialId;
                                itdata.StorId = Locationdata.StorId;
                                itdata.LocalId = LocationId;
                                itdata.Nums_O = 1;
                                itdata.Nums_N = 0;
                                itdata.CreatorId = _operator.UserId;
                                itdata.CreateTime = DateTime.Now;
                                itdata.Deleted = false;
                                itdata.AreaId = Locationdata.AreaId;
                                itdata.RackId = Locationdata.RackId;
                                itdata.ScanNum = 1;
                                itdata.CheckNum = 0;
                                LocalMaterialList.Add(itdata);
                            }
                            else if (jobdata.OldOrNew == 1)
                            {
                                //不存在新增
                                IT_LocalMaterial itdata = new IT_LocalMaterial();
                                itdata.Id = IdHelper.GetId();
                                itdata.MaterialId = jobdata.MaterialId;
                                itdata.StorId = Locationdata.StorId;
                                itdata.LocalId = LocationId;
                                itdata.Nums_O = 0;
                                itdata.Nums_N = 1;
                                itdata.CreatorId = _operator.UserId;
                                itdata.CreateTime = DateTime.Now;
                                itdata.Deleted = false;
                                itdata.AreaId = Locationdata.AreaId;
                                itdata.RackId = Locationdata.RackId;
                                itdata.ScanNum = 1;
                                itdata.CheckNum = 0;
                                LocalMaterialList.Add(itdata);
                            }
                        }
                        else
                        {
                            //存在修改
                            if (jobdata.OldOrNew == 0)
                            {
                                sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_O,0)+1,ScanNum=IFNULL(ScanNum,0)+1 where StorId='" + Locationdata.StorId + "' and LocalId='" + LocationId + "' and MaterialId='" + jobdata.MaterialId + "'; ";
                            }
                            else if (jobdata.OldOrNew == 1)
                            {
                                sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+1,ScanNum=IFNULL(ScanNum,0)+1 where StorId='" + Locationdata.StorId + "' and LocalId='" + LocationId + "' and MaterialId='" + jobdata.MaterialId + "'; ";
                            }
                        }

                        //修改物料审核前数量
                        sqlMain += @" update PB_Material set ScanNum=IFNULL(ScanNum,0)+1 where Id='" + jobdata.MaterialId + "'; ";

                        //修改收货单的入库数量
                        sqlMain += @" update TD_RecDetail set InNum=IFNULL(InNum,0)+1 where RecId='" + ReceivingId + "' and MaterialId='" + jobdata.MaterialId + "'; ";
                    }
                    else
                    {
                        throw new BusException("请扫描正确的成品二维码");
                    }
                }

                await Db.InsertAsync<PB_Stock>(StockList);
                await Db.InsertAsync<PB_StockLog>(StockLogList);
                await Db.InsertAsync<PB_UpLoadList>(UpLoadListList);
                await Db.InsertAsync<IT_LocalDetail>(LocalDetailList);
                await Db.InsertAsync<IT_LocalMaterial>(LocalMaterialList);
                await Db.InsertAsync<PB_JobBookingQrCode>(JobBookingQrCode);
                await ExecuteSqlAsync(sqlMain);
            }
            else
            {
                throw new BusException("请扫描正确的收货单二维码");
            }
        }

        #region
        /// <summary>
        /// 获取收货单的已入库的明细信息
        /// </summary>
        /// <param name="receivingId">收货单Id</param>
        /// <returns></returns>
        public async Task<List<PB_UpLoadListDataDTO>> GetLocalMaterialOldAsync(string receivingId)
        {
            //            string sqlMain = @"select *,ROW_NUMBER() over(order by CreateTime desc) as rowsid from ( 
            //select a.Id,a.PackId,a.MaterialId,a.CirBillId,a.Nums as StockNumber,b.Id as BoxNo,b.Name as BoxName,(concat(d.`Name`,'/',e.`Name`,'/',c.`Name`)) as LocalName,b.Spec as MaterialSpec,a.CreateTime,a.LocalId as LocationId,f.StorId,'0' as OldOrNew,a.JobId from  PB_UpLoadList as a join PB_Material as b on a.MaterialId=b.Id  join PB_Location as c on a.LocalId=c.Id join PB_StorArea as d on c.AreaId=d.Id join PB_Rack as e on c.RackId=e.Id join PB_Location as f on a.LocalId=f.Id where a.ParentId='{0}' and a.PackId='' and a.JobId=''
            //UNION ALL 
            //select '' as Id,PackId,'' as MaterialId,CirBillId,SUM(StockNumber) as StockNumber,BoxNo,BoxName,LocalName, '' as MaterialSpec,CreateTime,LocationId,StorId,OldOrNew,'' as JobId from (select a.PackId,a.Nums as StockNumber,b.BoxNo,b.BoxName,(concat(d.`Name`,'/',e.`Name`,'/',c.`Name`)) as LocalName,DATE_FORMAT(a.CreateTime,'%Y-%m-%d') as CreateTime,a.LocalId as LocationId,f.StorId,b.OldOrNew,a.CirBillId from PB_UpLoadList as a join PB_PackList as b on a.PackId=b.Id join PB_Location as c on a.LocalId=c.Id join PB_StorArea as d on c.AreaId=d.Id join PB_Rack as e on c.RackId=e.Id join PB_Location as f on a.LocalId=f.Id  where a.ParentId='{0}' and b.PackageType=1 )as t group by PackId,BoxNo,BoxName,LocalName,CreateTime,LocationId,StorId,OldOrNew,CirBillId
            //UNION ALL 
            //select '' as Id,a.PackId,a.MaterialId,a.CirBillId,a.Nums as StockNumber,b.BoxNo,b.BoxName,(concat(d.`Name`,'/',e.`Name`,'/',c.`Name`)) as LocalName,f.Spec as MaterialSpec,a.CreateTime,a.LocalId as LocationId,g.StorId,b.OldOrNew,'' as JobId from PB_UpLoadList as a join PB_PackList as b on a.PackId=b.Id join PB_Location as c on a.LocalId=c.Id join PB_StorArea as d on c.AreaId=d.Id join PB_Rack as e on c.RackId=e.Id join PB_Material as f on a.MaterialId=f.Id join PB_Location as g on a.LocalId=g.Id where a.ParentId='{0}' and b.PackageType=0 
            //UNION ALL
            //select a.Id,a.PackId,a.MaterialId,a.CirBillId,a.Nums as StockNumber,a.JobId as BoxNo,b.Name as BoxName,(concat(d.`Name`,'/',e.`Name`,'/',c.`Name`)) as LocalName,b.Spec as MaterialSpec,a.CreateTime,a.LocalId as LocationId,f.StorId,g.OldOrNew,a.JobId from  PB_UpLoadList as a join PB_Material as b on a.MaterialId=b.Id  join PB_Location as c on a.LocalId=c.Id join PB_StorArea as d on c.AreaId=d.Id join PB_Rack as e on c.RackId=e.Id join PB_Location as f on a.LocalId=f.Id join IT_LocalDetail as g on a.JobId=g.JobId where a.ParentId='{0}' and a.PackId='' and a.JobId!=''
            //) as t";
            string sqlMain = @"select *,ROW_NUMBER() over(order by CreateTime desc) as rowsid from ( 
select a.Id,a.PackId,a.MaterialId,a.CirBillId,a.Nums as StockNumber,b.Id as BoxNo,b.Name as BoxName,(concat(d.`Name`,'/',e.`Name`,'/',c.`Name`)) as LocalName,b.Spec as MaterialSpec,a.CreateTime,a.LocalId as LocationId,f.StorId,'0' as OldOrNew,a.JobId from  PB_UpLoadList as a join PB_Material as b on a.MaterialId=b.Id  join PB_Location as c on a.LocalId=c.Id join PB_StorArea as d on c.AreaId=d.Id join PB_Rack as e on c.RackId=e.Id join PB_Location as f on a.LocalId=f.Id where a.ParentId='{0}' and a.PackId='' and a.JobId=''
UNION ALL 
select '' as Id,PackId,'' as MaterialId,CirBillId,SUM(StockNumber) as StockNumber,BoxNo,BoxName,LocalName, '' as MaterialSpec,CreateTime,LocationId,StorId,OldOrNew,'' as JobId from (select a.PackId,a.Nums as StockNumber,b.BoxNo,b.BoxName,(concat(d.`Name`,'/',e.`Name`,'/',c.`Name`)) as LocalName,DATE_FORMAT(a.CreateTime,'%Y-%m-%d') as CreateTime,a.LocalId as LocationId,f.StorId,b.OldOrNew,a.CirBillId from PB_UpLoadList as a join PB_PackList as b on a.PackId=b.Id join PB_Location as c on a.LocalId=c.Id join PB_StorArea as d on c.AreaId=d.Id join PB_Rack as e on c.RackId=e.Id join PB_Location as f on a.LocalId=f.Id  where a.ParentId='{0}' and b.PackageType=1 )as t group by PackId,BoxNo,BoxName,LocalName,CreateTime,LocationId,StorId,OldOrNew,CirBillId
UNION ALL 
select '' as Id,a.PackId,a.MaterialId,a.CirBillId,a.Nums as StockNumber,b.BoxNo,b.BoxName,(concat(d.`Name`,'/',e.`Name`,'/',c.`Name`)) as LocalName,f.Spec as MaterialSpec,a.CreateTime,a.LocalId as LocationId,g.StorId,b.OldOrNew,'' as JobId from PB_UpLoadList as a join PB_PackList as b on a.PackId=b.Id join PB_Location as c on a.LocalId=c.Id join PB_StorArea as d on c.AreaId=d.Id join PB_Rack as e on c.RackId=e.Id join PB_Material as f on a.MaterialId=f.Id join PB_Location as g on a.LocalId=g.Id where a.ParentId='{0}' and b.PackageType=0 
UNION ALL
select a.Id,a.PackId,a.MaterialId,a.CirBillId,a.Nums as StockNumber,a.JobId as BoxNo,b.Name as BoxName,(concat(d.`Name`,'/',e.`Name`,'/',c.`Name`)) as LocalName,b.Spec as MaterialSpec,a.CreateTime,a.LocalId as LocationId,f.StorId,'1' AS OldOrNew,a.JobId from  PB_UpLoadList as a join PB_Material as b on a.MaterialId=b.Id  join PB_Location as c on a.LocalId=c.Id join PB_StorArea as d on c.AreaId=d.Id join PB_Rack as e on c.RackId=e.Id join PB_Location as f on a.LocalId=f.Id where a.ParentId='{0}' and a.PackId='' and a.JobId<>''
) as t";
            string sql = string.Format(sqlMain, receivingId);
            return await Db.GetListBySqlAsync<PB_UpLoadListDataDTO>(sql);
        }
#endregion
        /// <summary>
        /// 待维入库扫码物料码依据收货单获取剩余入库数量
        /// </summary>
        /// <param name="packQrod">包二维码物料二维码</param>
        /// <param name="RecId">收货单号</param>
        /// <returns></returns>
        public async Task<ReceivePackDetail> GetReceivePackDetail(string packQrcode, string RecId)
        {
            string packModel = packQrcode.Split(',')[0].ToString();
            if (packModel == "04")
            {


                //扫描单个物料
                var model = packQrcode.Split(',');
                string materialId = string.Empty;
                if (model.Length > 2)
                {
                    if (model.Length < 4)
                    {
                        throw new BusException("请扫描正确的二维码信息");
                    }
                    else
                    {
                        materialId = model?[3].ToString();
                    }
                }
                else
                {
                    materialId = model?[1].ToString();
                }
                //合并重复物料指向新的物料Id
                PB_Material materdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == materialId).FirstOrDefaultAsync();
                if (materdata == null)
                {
                    throw new BusException("物料不存在!");
                }

                var PB_Mater = await Db.GetIQueryable<PB_Material>().Where(m => m.Id == materialId).FirstOrDefaultAsync();
                var td_recdetail = await Db.GetIQueryable<TD_RecDetail>().Where(m => m.RecId == RecId && m.MaterialId == materialId).ToListAsync();
                var td_recdetailsum = td_recdetail.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, RecNum = x.Sum(i => i.RecNum) }).FirstOrDefault();
                if (td_recdetailsum==null) {
                    throw new BusException("请扫描正确的物料码!");
                }
                var pB_StockLog = await Db.GetIQueryable<PB_UpLoadList>().Where(m => m.ParentId == RecId && m.MaterialId == materialId).ToListAsync();
                var pB_StockLogsum = pB_StockLog.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, StockNumber = x.Sum(i => i.Nums) }).FirstOrDefault();
                ReceivePackDetail receivePackDetail = new ReceivePackDetail();
                receivePackDetail.RecId = RecId;
                receivePackDetail.MaterialId = materialId;
                receivePackDetail.Name = PB_Mater.Name;
                receivePackDetail.Code = PB_Mater.Code;
                receivePackDetail.Spec = PB_Mater.Spec;
                receivePackDetail.ReceivingQuantity = td_recdetailsum.RecNum;
                receivePackDetail.WarehousedQuantity = (pB_StockLogsum == null ? 0 : pB_StockLogsum.StockNumber);
                return receivePackDetail;
            }
            //扫描虚拟包
            else if (packModel == "99")
            {
                //扫描单个物料
                string materialId = packQrcode.Split(',')[1].ToString();
               
                //合并重复物料指向新的物料Id
                PB_Material materdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == materialId).FirstOrDefaultAsync();
                if (materdata == null)
                {
                    throw new BusException("物料不存在!");
                }

                var PB_Mater = await Db.GetIQueryable<PB_Material>().Where(m => m.Id == materialId).FirstOrDefaultAsync();
                var td_recdetail = await Db.GetIQueryable<TD_RecDetail>().Where(m => m.RecId == RecId && m.MaterialId == materialId).ToListAsync();
                var td_recdetailsum = td_recdetail.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, RecNum = x.Sum(i => i.RecNum) }).FirstOrDefault();
                var pB_StockLog = await Db.GetIQueryable<PB_UpLoadList>().Where(m => m.ParentId == RecId && m.MaterialId == materialId).ToListAsync();
                var pB_StockLogsum = pB_StockLog.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, StockNumber = x.Sum(i => i.Nums) }).FirstOrDefault();
                ReceivePackDetail receivePackDetail = new ReceivePackDetail();
                receivePackDetail.RecId = RecId;
                receivePackDetail.MaterialId = materialId;
                receivePackDetail.Name = PB_Mater.Name;
                receivePackDetail.Code = PB_Mater.Code;
                receivePackDetail.Spec = PB_Mater.Spec;
                receivePackDetail.ReceivingQuantity = td_recdetailsum.RecNum;
                receivePackDetail.WarehousedQuantity = (pB_StockLogsum == null ? 0 : pB_StockLogsum.StockNumber);
                return receivePackDetail;
            }
           
            return null;
        }

        public async Task<List<TD_RecDetailInfo>> GetTD_ReceivingInfo(string QrCode,string MaterName) {
            string RecId = QrCode.Split(',')[1].ToString();
            var TD_Receiving =await Db.GetIQueryable<TD_Receiving>().Where(m=>m.Id==RecId).FirstOrDefaultAsync();
   
            string sql = "SELECT a.MaterialId,b.`Name` Name,b.`Code` Code,b.Spec Spec,  a.RecNum,a.InNum FROM TD_RecDetail AS a LEFT JOIN PB_Material AS b on a.MaterialId = b.Id WHERE a.RecId = '"+ RecId + "'";
            if (!MaterName.IsNullOrEmpty()) {
                sql += " AND (b.`Name` LIKE '%"+MaterName+ "%' OR b.`Code` LIKE '%"+MaterName+"%' )";
            }
            List<TD_RecDetailInfo> listDetail =await Db.GetListBySqlAsync<TD_RecDetailInfo>(sql) ;
            return listDetail;
        }
        #endregion

        #region 私有成员

        #endregion
    }


}